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

          統計

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 萨嘎县| 南汇区| 宜兰县| 信丰县| 通化县| 雷州市| 呼和浩特市| 吴桥县| 南平市| 潮安县| 中西区| 麦盖提县| 饶河县| 赣榆县| 太谷县| 宝应县| 新巴尔虎左旗| 赤壁市| 阳山县| 同德县| 清远市| 新蔡县| 湖州市| 于田县| 大方县| 商都县| 慈溪市| 甘孜县| 郸城县| 墨玉县| 永新县| 昭觉县| 响水县| 咸丰县| 阿拉尔市| 商河县| 安龙县| 托里县| 尉犁县| 泾源县| 大田县|