dyllove98

庞果网编程英雄会上做的一道题:二分查找(非递归),和大家分享一下:

 

public class BinarySearchClass
{

    public static int binary_search(int[] array, int value)
    {
        int beginIndex = 0;// 低位下标
        int endIndex = array.length - 1;// 高位下标
        int midIndex = -1;
        while (beginIndex <= endIndex) {
            midIndex = beginIndex + (endIndex - beginIndex) / 2;//防止溢出
            if (value == array[midIndex]) {
                return midIndex;
            } else if (value < array[midIndex]) {
                endIndex = midIndex - 1;
            } else {
                beginIndex = midIndex + 1;
            }
        }
        return -1;
        //找到了,返回找到的数值的下标,没找到,返回-1       
    }


    //start 提示:自动阅卷起始唯一标识,请勿删除或增加。
    public static void main(String[] args)
    {
        System.out.println("Start...");
        int[] myArray = new int[] { 1, 2, 3, 5, 6, 7, 8, 9 };
        System.out.println("查找数字8的下标:");
        System.out.println(binary_search(myArray, 8));        
    }
    //end //提示:自动阅卷结束唯一标识,请勿删除或增加。
}   


 

 

分类:

技术点:

相关文章:

  • 2021-11-13
  • 2020-06-25
  • 2021-12-20
  • 2018-12-18
  • 2019-11-03
  • 2021-07-26
  • 2021-12-03
  • 2021-12-10
猜你喜欢
  • 2020-07-30
  • 2021-09-29
  • 2021-07-22
  • 2020-07-30
  • 2021-11-30
  • 2018-07-29
  • 2021-12-10
相关资源
相似解决方案