码迷,mamicode.com
首页 > 其他好文 > 详细

折半查找(二分查找)

时间:2014-08-12 00:30:13      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   java   os   ar   art   div   

import java.util.Arrays;

/*
 * 二分查找
 */
public class BinarySearch {

    /*
     * while循环
     */
    public static int binarySearch(int[] ls, int su) {
        int low = 0;
        int high = ls.length - 1;

        while (low <= high) {
            int avg = (low + high) / 2;
            if (su == ls[avg]) {
                return avg;
            } else if (su > ls[avg]) {
                low = avg + 1;
            } else if (su < ls[avg]) {
                high = avg - 1;
            }
        }

        return -1;
    }

    /*
     * 递归
     */
    public static int binarySearch(int[] ls, int startindex, int endindex,
            int su) {
        int avg = (startindex + endindex) / 2;
        if (startindex > endindex || su < ls[startindex] || su > ls[endindex]) {
            return -1;
        }
        if (su == ls[avg]) {
            return avg;
        } else if (su > ls[avg]) {
            return binarySearch(ls, avg + 1, endindex, su);
        } else if (su < ls[avg]) {
            return binarySearch(ls, startindex, avg - 1, su);
        }

        return -1;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] ls = { 3, 6, 4, 9, 8, 12, 13, 21, 5, 16, 7, 0, 1, 2 };
        // 排序
        Arrays.sort(ls);

        System.out.println(Arrays.toString(ls));

        int su = 16;
        // while 循环
        System.out.println(binarySearch(ls, su));
        // 递归
        System.out.println(binarySearch(ls, 0, ls.length - 1, su));
        // Arrays 方法
        System.out.println(Arrays.binarySearch(ls, su));
    }

}

 

输出
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 16, 21]
11
11
11

 

折半查找(二分查找),布布扣,bubuko.com

折半查找(二分查找)

标签:style   blog   color   java   os   ar   art   div   

原文地址:http://www.cnblogs.com/loveismile/p/3906043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!