任何人都可以指出我在哪裏出錯了嗎?我用一個調試器遍歷它,它看起來像我的算法應該找到搜索關鍵字,但它不是。 (爲了檢查,我打印出'在索引處找到',然後打印[sorted]列表的內容;我搜索的元素123位於列表中,但返回了'not found'值-1。)BinarySearch在列表中找不到元素:Java
public int binarySearch(ArrayList<Integer> list, int key){
int foundAtIndex = -1;
int midPoint = list.size()/2;
int midPointValue = list.get(midPoint);
if(list.size() > 1){
if(midPointValue == key){
foundAtIndex = midPoint;
}
else if(midPointValue > key){
ArrayList<Integer> newList = new ArrayList<Integer>();
for(int i = 0; i < midPoint; i++){
newList.add(list.get(i));
}
midPoint = midPoint/2;
binarySearch(newList, key);
}
else if(midPointValue < key){
ArrayList<Integer> newList = new ArrayList<Integer>();
for(int j = midPoint+1; j < list.size(); j++){
newList.add(list.get(j));
}
midPoint = midPoint/2;
binarySearch(newList, key);
}
}
else if(list.size() == 1){
if(list.get(0) == key){
foundAtIndex = 0;
}
}
//return the index where the key was found, or -1 if not found
return foundAtIndex;
}
編輯:好的,所以它發現它了,但我的問題是我需要在原數組返回發現索引。實際上,它縮小了它,然後返回'newList'中元素的索引。所以它會一直以「newList」的形式返回索引。換句話說,我正在尋找返回一個實際的foundAtIndex(在原始數組中的值位於什麼位置),而不是一個布爾值,「was/was not found」值。
,你是循環建立的子名單,這一事實並沒有那麼大。考慮使用初始數組並傳遞開始和結束參數以及初始列表。 – aepheus 2011-05-05 21:52:00
看到我下面更新的答案。它解決了返回正確索引的問題 – 2011-05-06 22:57:11