浏览 2237 次
锁定老帖子 主题:二分排序 例子
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-10-19
最后修改:2011-10-19
例如 刚开始 : int[] numbers = { 1, 12, 13, 34, 35, 56, 57,92, 99,101,102,104,105,109,110,115,166,300,400,500}; 交换后的结果: int[] numbers = {92, 99,101,102,104,105,109,110,115,166,300,400,500, 1, 12, 13, 34, 35, 56, 57}; 直接给算法答案: public class Test { /** * @param args */ public static void main(String[] args) { int[] numbers = {92, 99,101,102,104,105,109,110,115,166,300,400,500, 1, 12, 13, 34, 35, 56, 57}; // System.out.println(Test.getPosition(numbers, 0)); // System.out.println(Test.getPosition(numbers, 1)); // System.out.println(Test.getPosition(numbers, 11)); // System.out.println(Test.getPosition(numbers, 13)); // System.out.println(Test.getPosition(numbers, 33)); // System.out.println(Test.getPosition(numbers, 35)); // System.out.println(Test.getPosition(numbers, 43)); // System.out.println(Test.getPosition(numbers, 57)); // System.out.println(Test.getPosition(numbers, 66)); // System.out.println(Test.getPosition(numbers, 92)); // System.out.println(Test.getPosition(numbers, 97)); // System.out.println(Test.getPosition(numbers, 99)); // System.out.println(Test.getPosition(numbers, 100)); System.out.println(Test.getPosition(numbers, 400)); } private static int getPosition(int[] numbers, int number) { int seperator = numbers[0]; int low = 0; int high = numbers.length - 1; while(low < high) { int mid = (low + high)/2; int midNumber = numbers[mid]; if(midNumber == number) { return mid; } if(number == seperator) { return low; } if(number > seperator) { if(number > midNumber&& midNumber >= seperator) { low = mid + 1; }else { high = mid - 1; } }else { if(number < midNumber&& midNumber < seperator) { high = mid - 1; }else { low = mid + 1; } } } if(high >= 0&& numbers[high] == number) { return high; } if(low < numbers.length&& numbers[low] == number) { return low; } return -1; } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |