zoukankan      html  css  js  c++  java
  • Java 二分查找法

     二分查找是一种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组已经为空,则表示找不到指定的元素。这种搜索算法每一次比较都使搜索范围缩小一半,其时间复杂度是O(logN)。

    二分查找法代码实现: 

    package cn.latiny.algorithma;
    
    /**
     * @author Latiny
     * @version 1.0
     * @description: 二分查找法
     * @date 2019/7/18 11:18
     */
    public class BinarySort {
    
        public static void main(String[] args) {
            int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            System.out.println(binarySortRecursion(array, 5, 0, array.length - 1));
            System.out.println(binarySort(array, 5));
        }
    
        /**
         * 循环实现二分查找
         *
         * @param array
         * @param key
         * @return
         */
        public static int binarySort(int[] array, int key) {
            int low = 0;
            int high = array.length - 1;
            while (low <= high) {
                int mid = (low + high) >>> 1;
                if (key < array[mid]) {
                    high = mid - 1;
                } else if (key > array[mid]) {
                    low = mid + 1;
                } else {
                    return mid;
                }
            }
            return -1;
        }
    
        /**
         * 递归实现二分查找
         *
         * @param array
         * @param key
         * @param low
         * @param high
         * @return
         */
        public static int binarySortRecursion(int[] array, int key, int low, int high) {
            if (low <= high) {
                int mid = (low + high) >>> 1;
                if (key < array[mid]) {
                    return binarySortRecursion(array, key, low, mid - 1);
                } else if (key > array[mid]) {
                    return binarySortRecursion(array, key, mid + 1, high);
                } else {
                    return mid;
                }
            }
            return -1;
        }
    
    }
    View Code
  • 相关阅读:
    ★一名“标题党”自我修炼的10大技巧
    字符编码笔记:ASCII,Unicode和UTF-8
    字符编码笔记:ASCII,Unicode和UTF-8
    字符编码笔记:ASCII,Unicode和UTF-8
    ★漫画:优秀的程序员具备哪些属性?
    ★漫画:优秀的程序员具备哪些属性?
    Linux 标准目录结构
    hadoop多次格式化后,导致datanode启动不了
    Linux天天见
    我的ipad应用备份
  • 原文地址:https://www.cnblogs.com/Latiny/p/10527204.html
Copyright © 2011-2022 走看看