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 閱讀(196) 評論(0)  編輯  收藏 所屬分類: java


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

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

          統計

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 江安县| 麟游县| 房山区| 定边县| 铜川市| 建阳市| 常熟市| 镇雄县| 盐边县| 海晏县| 隆尧县| 榆树市| 鄂伦春自治旗| 北碚区| 乃东县| 元朗区| 龙胜| 恩平市| 新龙县| 广河县| 达孜县| 长乐市| 清丰县| 寻甸| 平邑县| 张北县| 荆州市| 叶城县| 浦东新区| 札达县| 利辛县| 海南省| 海兴县| 宿迁市| 铅山县| 宜昌市| 舞阳县| 漯河市| 太和县| 瑞金市| 集安市|