java 折半查找

 1package com.test2;
 2
 3public class Demo2 {
 4
 5    /**
 6     * @param args
 7     */

 8
 9    public static int search(int[] arrays, int target) {
10
11        int start = 0;
12        int end = arrays.length - 1;
13        int pos;
14        while (start <= end) {
15            pos = (start + end) / 2;
16            if (arrays[pos] == target) {
17                return pos;
18            }
 else if (arrays[pos] > target) {// 如果数组中间的数大于目标,则将end的位置变成数组中间位置-1的位置
19                end = pos - 1;
20            }
 else {
21                start = pos + 1;// 如果数组中间的数小于目标,则将start的位置变成数组中间位置+1的位置
22            }

23        }

24        return -1// 若没有查找到,则返回-1
25    }

26
27    public static void main(String[] args) {
28        int[] arrays = 232839592883223242323 };
29        System.out.println(search(arrays, 28));
30        System.out.println(search(arrays, 322));
31        System.out.println(search(arrays, 59));
32        System.out.println(search(arrays, 288));
33    }

34
35}

36

posted on 2012-11-17 08:30 skylight 阅读(164) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2012年11月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜