《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 三个变量来保存每一步搜索的范围. 以下程序描写了怎样数组排序,这样你就可以使用二分搜索法了.
相关文章推荐
- 《Java 编程技巧1001条》 第392条: 了解2分查找
- 《Java 编程技巧1001条》第415条:使用keyDown方法
- 《Java 编程技巧1001条》 第399条:对原始类型数组使用数组复制
- 《Java 编程技巧1001条》 第420...条: 使用handle event 方法
- 《Java 编程技巧1001条》第416条:使用keyUp方法
- 《Java 编程技巧1001条》第391条: 在数组中查找一指定值
- 《Java 编程技巧1001条》 第400条: 使用数组复制
- 《Java 编程技巧1001条》 第406条: 使用mouseUp方法
- 《Java 编程技巧1001条》第409...条: 使用crickCount方法,
- 《Java 编程技巧1001条》 第407条:使用mouseDrag方法,
- 《Java 编程技巧1001条》 第395与396条 :了解和使用冒泡排序
- 《Java 编程技巧1001条》第413条:使用mouseEnter 和 mouseExit
- 《Java 编程技巧1001条》 第405条: 使用mouseDoun方法
- 《Java 编程技巧1001条》 第408条: 使用mouseMove方法,
- 《Java 编程技巧1001条》 第397+398条:了解和使用快速排序
- 《Java 编程技巧1001条》 第404条: 了解实用方法
- 《Java 编程技巧1001条》 第403条: 了解事件类
- 【编程技巧】java不使用第三个变量处理两个变量的交换
- 《Java 编程技巧1001条》 第382+283条: 了解数组的长度和引用
- 《Java 编程技巧1001条》第401条:数组中存不同对象