Exercise1.1.29 等值键

来源:互联网 发布:金蝶k3无法数据引出 编辑:程序博客网 时间:2024/06/06 01:33
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));    }}
0 0
原创粉丝点击