import java.util.Arrays;
public class BinarySearch {
public static int rank(int key, int[] tar) {
Arrays.sort(tar);
int low = 0;
int high = tar.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (key == tar[mid]) {
return mid;
} else if (key < tar[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
public static int find(int key, int[] array) {// 找出array中所有小于key的个数
int judge = rank(key, array);
if (judge != -1) {
int index = judge;
int i=0;
while ( (i=index-1) >= 0 && array[--index] == key) {
}
return index + 1;
}
return -1;
}
public static int count(int key, int[] array) {// 找出array中和key相等的元素
int judge = rank(key, array);
if (judge != -1) {
int index = judge;
int index1 = index;
int index2 = index;
int sum = 1;
int i=0;
while ((i=index1-1) >= 0 && array[--index1] == key) {
sum++;
}
while ((i=index2+1) < array.length && array[++index2] == key) {
sum++;
}
return sum;
}
return -1;
}
public static void main(String[] args) {
int[] array = { 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6, 7, 8, 9 };
System.out.println("find " + find(9, array));
System.out.println("count " + count(9, array));
}
}
Exercise1.1.29 等值键
最新推荐文章于 2021-01-22 12:17:55 发布