您的位置:首页 > 编程语言 > Java开发

《Java 编程技巧1001条》 第393条: 使用2分查找

2017-12-23 10:24 537 查看



《Java 编程技巧1001条》第10章 用数组存储数据 第393条 使用2分查找 

393 Using a binary search
393 使用二分法搜索

You havelearned that aA binary search is an efficient algorithm for searching through asorted array. The technique of how to implement the binary search is bestdemonstrated with an example. To demonstrate the binary search technique, Tthefollowing program looks throughsearches an array of integers for variousvalues. AsWhen you execute the program executes, it prints messages are printedto the screen that describe the process of the search. Also, at the end of thesearch, the program displays the number of steps it required to find thedesired valueby the binary search: to the screen:
你已知道二分法搜索是对排好序的数组的一种非常有效的搜索算法. 怎样实现二分法搜索的过程最好是通过一个例子来说明. 以下程序通过对一个整型数组寻找某个值来说明二分搜索法. 当此程序执行时,描述搜索过程的信息将在屏幕上打印出来. 并且,在搜索完毕后,程序将在屏幕上显示用二分法找到需要的数值所需的步数: public classarrayBinary {    public static int bsearch(int array[], intvalue)     {       boolean found = false;       int high = array.length - 1;       int low = 0;       int cnt = 0;       int mid = (high + low)/2;              System.out.println("Looking for" + value);        while (!found && (high >=low))         {           System.out.print("Low " +low +  " Mid " + mid);           System.out.println(" High" + high);            if (value == array[mid])             {               found = true;             }            else if (value < array[mid])              high = mid - 1;           else              low = mid + 1;            mid = (high + low)/2;            cnt++;         }        System.out.println("Steps " +cnt);             return((found) ? mid: -1);     }    public static void main(String[] args)     {       int array[] = new int[100];        for (int i=0; i < array.length; i++)         {           array[i] = i;         }       System.out.println("Results " +bsearch(array,67));      System.out.println("Results " +bsearch(array,33));      System.out.println("Results " +bsearch(array,1));      System.out.println("Results " +bsearch(array,1001));   } }
Fromthis programs output, you can see how a binary search sub-divides an array. Theprogram uses the high, mid, and low variables to keep track of the ranges for each stepof the search. The following tips describe how to sort an array, so that youmay use the binary search technique.
从此程序的输出,你可看到二分法搜索是怎样分划一个数组的. 程序利用了high, mid和 low 三个变量来保存每一步搜索的范围. 以下程序描写了怎样数组排序,这样你就可以使用二分搜索法了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: