zoukankan      html  css  js  c++  java
  • 折半查找法

    折半查找法的前提下就是排好序的数组。算了,直接上代码吧,思路就是每次都拿中间的数比较,大于中间数的就取后面一段数继续比较,否则就取前面的一段数继续比较

    static int[] a={1,3,5,6,9,10,29};//定义一组测试的数组
        static int b=9;//要从数组里面查找的数
        public static void main(String[] args) {
            
            int result = search(0, a.length-1, b);
            System.out.println(result);
            
        }
        public static int search(int start,int end,int value){
            if(a[start]==value){
                return start;
            }
            if(a[end]==value){
                return end;
            }
            if(start>=end||start+1==end||a[start]>value||a[end]<value){
                return -1;
            }
            
            int middle=(start+end)/2;
            if(value>a[middle]){
                start=middle;
                return search(start, end, value);
            }else if(value<a[middle]){
                end=middle;
                return search(start, end, value);
            }else{
                return middle;//找到了
            }
        }

    运行结果:

  • 相关阅读:
    firstResponder
    形而上学
    du -h
    数据本地存贮与数据结构(对象)
    RFC
    oc语言源代码
    HTTP1.1协议中文版-RFC2616
    如何提高团队协作的效率
    iOS应用架构谈 开篇
    nginx版本如何选择?
  • 原文地址:https://www.cnblogs.com/pig-brother/p/7364007.html
Copyright © 2011-2022 走看看