标签:
package algorithm;
public class BinarySearch {
public static int search(int a[], int key) {
int low = 0;
int high = a.length - 1;
int mid = 0;
while (low <= high) {
mid = (low + high)/2;
if (a[mid] == key) {
return mid;
} else if (a[mid] > key){
high = mid -1;
} else {
low = mid + 1;
}
}
return mid;
}
/**
* 重复的要取最小index的那个
* @param a
* @param key
* @return
*/
public static int search2(int a[], int key) {
int low = 0;
int high = a.length - 1;
int mid = 0;
while (low <= high) {
mid = (low + high)/2;
if (a[mid] >= key){
if (a[mid] == key) {
if (mid == 0 || a[mid - 1] != key) {
return mid;
}
}
high = mid -1;
} else {
low = mid + 1;
}
}
return mid;
}
public static void main(String[] args) {
int a[] = {5,13,19,21,21,21,37,56,56,56,64,75,80,88,92};
System.out.println(search2(a, 21));
System.out.println(search2(a, 56));
}
}
标签:
原文地址:http://www.cnblogs.com/godfatherback/p/5841734.html