zoukankan      html  css  js  c++  java
  • 二分法查找数组中元素

    要使用二分法需要注意:  数组中的元素必须已经按升序排列好

    二分法主要思想是将一个数组一分为二,每次查询都能将查询范围在上一次的基础上缩小一半。所以效率非常高。

    下面是Java代码实现:

    import java.util.*; 
    
    public class Main
    {
    
        public static void main(String[] args) throws Exception
        {
            Integer[] numbers = new Integer[] 
            {
                    1,3,2,1,2,3,2,7,7,8,2
            };
            Integer target = 7;
            Integer head = 0;
            Integer tail = numbers.length - 1;
            Integer middle = (head + tail)/2;
            
            Arrays.sort(numbers); 
            for(Integer item : numbers)
                System.out.print(item + " ");
            System.out.println();
            Integer targetIndex = dichotomySearch(numbers,head,middle,tail,target);
            if(targetIndex == null)
                System.out.println("target not found");
            else
                System.out.println("target in: " + targetIndex);
        }
        
        public static Integer dichotomySearch(Integer[] numbers,Integer head, Integer middle,Integer tail,Integer target)
        {
            //System.out.println("head:" + head + " middle:" + middle + " tail:" + tail);
            if(target.equals(numbers[head]))
                return head;
            if(target.equals(numbers[middle]))
                return middle;
            if( target.equals(numbers[tail]))
                return tail;
            
            
            if(head.equals(middle) || head.equals(tail)||middle.equals(tail))
                return null;
            
            if(target.compareTo(numbers[head]) > 0 && target.compareTo(numbers[middle]) < 0)
            {
                System.out.println("A");
                tail = middle;
                middle = (head + tail)/2;
            }
            else if(target.compareTo(numbers[middle]) > 0 && target.compareTo(numbers[tail]) < 0)
            { 
                head = middle;
                middle = (head + tail)/2; 
            }
            else
            {
                return null;
            }
            
            return dichotomySearch(numbers, head,  middle, tail, target);
        } 
    }

    输出结果:

    1 1 2 2 2 2 3 3 7 7 8
    target in: 8

  • 相关阅读:
    HDU1879 kruscal 继续畅通工程
    poj1094 拓扑 Sorting It All Out
    (转)搞ACM的你伤不起
    (转)女生应该找一个玩ACM的男生
    poj3259 bellman——ford Wormholes解绝负权问题
    poj2253 最短路 floyd Frogger
    Leetcode 42. Trapping Rain Water
    Leetcode 41. First Missing Positive
    Leetcode 4. Median of Two Sorted Arrays(二分)
    Codeforces:Good Bye 2018(题解)
  • 原文地址:https://www.cnblogs.com/kuillldan/p/5701338.html
Copyright © 2011-2022 走看看