我有以下問題需要解決,但是有點困難。如果有人能提供幫助,我會非常感激。JAVA - 二進制搜索 - 鍵值返回索引
總之在歸結爲如下:
- 如果搜索關鍵字是該陣列中 - 它返回最小的索引i針對其[i]是等於鍵
- 如果搜索關鍵字不在數組中,但是更大 - 它返回最小索引i作爲-i,其中a [i]大於關鍵字
- 如果搜索關鍵字不在數組中但更小 - 則返回-j其中j是陣列中最後一個元素的索引
我有搜索關鍵字的代碼,但我不知道上述如何返回指數...
import java.util.Arrays;
public class BinarySearchIndex2 {
// a working recursive version
public static int search(String key, String[] a) {
return search(key, a, 0, a.length);
}
public static int search(String key, String[] a, int lo, int hi) {
// possible key indices in [lo, hi)
if (hi <= lo) return -1;
int mid = lo + (hi - lo)/2;
int cmp = a[mid].compareTo(key);
if (cmp > 0) return search(key, a, lo, mid);
else if (cmp < 0) return search(key, a, mid+1, hi);
else return mid;
}
public static void main(String[] args) {
String key = args[0];
int sizeoflist = StdIn.readInt();
String[] a = new String[sizeoflist];
int counter = 0; //counter for while loop to fill array a
while (!StdIn.isEmpty()){
a[counter] = StdIn.readString();
counter++;
}
Arrays.sort(a); // sort the words (if needed)
if (search(key, a) < 0) ; /* System.out.println();*/
else if (search(key, a) > 0) ;
else if (search(key, a) = 0) ;
}
}
會很高興,如果有人能幫助我與這件事.. 。
謝謝!
b.t.w - 這是一項家庭作業嗎? (如果是這樣,請相應標記) – RonK 2011-04-25 20:05:36