美文网首页
二分查找(Java)

二分查找(Java)

作者: osingle | 来源:发表于2018-01-11 16:39 被阅读0次

    二分查找的前提是数组有序。   下面是代码:

    public class BinarySearch {

    int binarySearch(int a[],int key){

    int high,low,position;

    high=a.length-1;

    low=0;

    while(high>=low){

    position = (low+high)/2;

    if(a[position]==key){

    return position;

    }

    else if(a[position]>key){

    high=position - 1;

    }

    else{

    low = position + 1;

    }

    }

    return -1;

    }

    public static void main(String args[]){

    int a[]={1,2,3,4,5,6,7,8};

    BinarySearch b=new BinarySearch();

    System.out.println(b.binarySearch(a, 2));

    }

    };


    说说关键吧! 二分查找很简单,因此重要的是要在很短时间内将二分查找写出来。因此需要记忆的是while 循环的条件是high>=low 不是>low。 其他的好像没什么困难的。二分查找的时间复杂度是O(logn)

    相关文章

      网友评论

          本文标题:二分查找(Java)

          本文链接:https://www.haomeiwen.com/subject/wlktoxtx.html