二分查找是在已经排序完成的基础上进行的,每次选择数组中间的元素进行比较,如果比较的元素小于中间的元素,则将比较的元素对应的索引值赋值给末尾元素对应的索引。如果大于中间的元素,则将比较的元素对应的索引值赋值给开始元素对应的索引。
图解:
代码:
public class BinarySearch {
static int a[] = { 0, 1, 2, 3, 4, 7,9 };
public static void main(String[] args) {
int b[] = sort(a);
for (int i : b) {
System.out.print(i+" ");
}
System.out.println();
System.out.println(find(b, 9));
}
public static int[] sort(int[] a) {
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
return a;
}
public static int find(int a[], int n) {
int start = 0;
int end = a.length-1;
for (int i = 0; i < a.length / 2; i++) {
int middle = (start + end) / 2;
if (a[middle] > n) {
end = middle-1;
} else if (a[middle] < n) {
start = middle+1;
} else {
return middle;
}
}
return -1;
}
}