【java学习笔记19】数组排序算法之二分查找(适用于有序排列的数组)

package ArraySorted;

public class ArrayTest05 {

    public static void main(String[] args) {

        // 二分查找的前提是,数组必须有序

        int[] array = {10,20,30,40,50,60,70,80};

        int index = getIndexByEle(array,77);
        System.out.println(index);
    }

    private static int getIndexByEle(int[] array, int ele) {

        int minIndex = 0;
        int maxIndex = array.length - 1;
        int cenIndex = (minIndex + maxIndex) / 2;

        while (minIndex <= maxIndex){
            if (ele == array[cenIndex]){
                return cenIndex;
            } else if (ele > array[cenIndex]){
                minIndex = cenIndex + 1;
            } else if (ele < array[cenIndex]){
                maxIndex = cenIndex - 1;
            }

            // 重新计算
            cenIndex = (minIndex + maxIndex)/2;
        }
        return -1;


    }
}

 

分别测试一下代码!

输入元素20,返回1;

输入元素70,返回6;

输入元素77,返回-1。

 

posted @ 2021-01-05 21:07  愚人李愚  阅读(149)  评论(0编辑  收藏  举报