二進制搜索是一種在排序列表上有效工作的搜索技術。 因此,要使用二進制搜索技術來搜索某個列表中的元素,需要確保對列表是一個已排好順序。
二進制搜索遵循分而治之的方法,其中,列表被分成兩半,並且項目與列表的中間元素進行比較。 如果找到匹配,則返回中間元素的位置,否則根據匹配產生的結果搜索到兩半中的任何一個。
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100};
int item = 90;
int location = binarySearch(arr, 0, 9, item);
if (location != -1)
System.out.println("the location of the item is " + location);
else
System.out.println("Item not found");
}
public static int binarySearch(int[] data, int begin, int end, int item) {
int mid;
if (end >= begin) {
mid = (begin + end) / 2;
if (data[mid] == item) {
return mid;
} else if (data[mid] < item) {
return binarySearch(data, mid + 1, end, item);
} else {
return binarySearch(data, begin, mid - 1, item);
}
}
return -1;
}
}