[java]代码库
package com.bdqn.yingyun;
public class ZheBan {
public static void main(String[] args) {
// 数组必须是有序的数组,且数字不能重复
int[] arr = { 1, 4, 5, 25, 35, 33, 76 };
int index = halfindex(arr, 8);
System.out.println("index=" + index);
}
//比较好用些
public static int halfindex(int[] arr, int key) {
int min, mid, max;
min = 0;
max = arr.length - 1;
while (min <= max) {
mid = (min + max) / 2;
if (key > arr[mid])
min = mid + 1;
else if (key < arr[mid])
max = mid - 1;
else
return mid;
}
return -1;
}
/* public static int halfindex_2(int[] arr, int key) {
int min, mid, max;
min = 0;
max = arr.length - 1;
mid = (min + max) / 2;
while (arr[mid] != key) {
if (key > arr[mid])
min = mid + 1;
else if (key < arr[mid])
max = mid - 1;
if (max < min)
return -1;
mid = (min + max) / 2;
}
return mid;
}*/
}