java 折半查找法(二分查找)实例
程序员文章站
2023-12-10 20:56:58
复制代码 代码如下:public class halfsearch { public static int halfsearch(int a[], int x)...
复制代码 代码如下:
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);
}
}