• 二分查找


    package foo;
    
    import java.util.Arrays;
    
    public class Main {
        
        /**
         * 二分查找
         * @param key 搜索的目标
         * */
        private static int binarySearch(int[] a, int fromIndex, int toIndex, int key) {
            int low = fromIndex;
            int high = toIndex - 1;
            int mid, midVal;
            while (low <= high) {
                mid = (low + high) >>> 1;
                midVal = a[mid];
                if (midVal < key)
                    low = mid + 1;
                else if (midVal > key)
                    high = mid - 1;
                else
                    return mid; // key found
            }
            return -(low + 1);  // key not found.
        }
        
        public static void main(String[] args) throws Exception {
            int[] a = new int[]{1,2,3,4,5};
            System.out.println(binarySearch(a, 0, a.length, 0));
            System.out.println(binarySearch(a, 0, a.length, 1));
            System.out.println(binarySearch(a, 0, a.length, 2));
            System.out.println(binarySearch(a, 0, a.length, 3));
            System.out.println(binarySearch(a, 0, a.length, 4));
            System.out.println(binarySearch(a, 0, a.length, 5));
            System.out.println(binarySearch(a, 0, a.length, 6));
        }
    }

    折半查找法也称为二分查找法,它充分利用了元素间的次序关系,采用分治策略,可在最坏的情况下用O(log n)完成搜索任务。优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。

  • 相关阅读:
    匿名对象
    封装性
    1 Django初探
    8 定制10MINs 3
    7 定制10MINs首页2
    5-1 练习css 总结
    6.定制10MINS首页1
    3-1 练习 HTML 总结
    5. css定位 居中
    4 CSS的20/80个知识点
  • 原文地址:https://www.cnblogs.com/qrlozte/p/3810877.html
Copyright © 2020-2023  润新知