Fork me on GitHub

Java排序——二分查找法

package Array;

public class array {
    public static void main(String[] args) {
        int [] array = {11,22,33,44,55,66,77,88,99};
        int index = binarySearch(array,44);
        System.out.println(index);
    }

    public static int binarySearch(int[] arr,int searchElement){
        int start = 0;
        int end  = arr.length-1;
        int searchElementIndex = -1;//返回值
        while (start<=end){
            int middleIndex = (start + end)/2;
            int middleElement = arr[middleIndex];

            if (middleElement == searchElement){
                searchElementIndex = middleIndex;//将中间元素的索引给元素的索引
                break;
            }else if (middleElement > searchElement){//中间元素大于要查找的值
                end = middleIndex - 1;
            }else if (middleElement < searchElement){//中间元素小于要查找的值
                start = middleIndex + 1;
            }
        }
        return searchElementIndex;
    }
}

 

posted @ 2021-07-06 11:41  Blueshadow^_^  阅读(75)  评论(0编辑  收藏  举报