当前位置: 编程技术>java/j2ee
java 折半查找法(二分查找)实例
来源: 互联网 发布时间:2014-10-23
本文导语: 代码如下: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 -...
代码如下:
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);
}
}