二分排序

来源:互联网 发布:mac 安装包已损坏 编辑:程序博客网 时间:2024/06/02 19:43
public class BinarySearch {    public static void main(String[] args) {        int[] arr = new int[]{7,10, 11, 12, 16, 18, 23, 29, 33, 48, 54, 57, 68, 77, 84, 98};        int index = search(arr, 29);        System.out.println(index);    }    public static int search(int[] arr, int key) {        int index = -1;        int startIndex = 0;        int endIndex = arr.length-1;        int middleIndex = -1;        while(startIndex <= endIndex) {            middleIndex = (startIndex + endIndex)/2;            if(key < arr[middleIndex]) {                endIndex = middleIndex - 1;            }else if(key > arr[middleIndex]) {                startIndex = middleIndex + 1;            }else {                index = middleIndex;                break;            }        }        return index;    }}
原创粉丝点击