代碼如下:
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);
}
}