java 折半查找法(二分查找)实例
作者:
java 折半查找法(二分查找)实例,需要的朋友可以参考一下
复制代码 代码如下:
public class HalfSearch {
public static int halfSearch(int a[], int x) {
int mid, left, right;
left = 0;
right = a.length - 1;
mid = (left + right) / 2;
while (a[mid] != x) {
if (x > a[mid]) {
left = mid + 1;
}
else if (x < a[mid]) {
right = mid - 1;
}
mid=(left+right)/2;
}
return mid;
}
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5, 6,7,8,9,10 };
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
int s = 10;
int index = halfSearch(a, s);
System.out.println(s + "在数组中的下标是 " + index);
}
}