二分法检索
二分法检索(binary search)又称折半检索,二分法检索的基本思想是设字典中的元素从小到大有序地存放在数组(array)中,
首先将给定值key与字典中间位置上元素的关键码(key)比较,如果相等,则检索成功;
否则,若key小,则在字典前半部分中继续进行二分法检索;
若key大,则在字典后半部分中继续进行二分法检索。
这样,经过一次比较就缩小一半的检索区间,如此进行下去,直到检索成功或检索失败。
偶数个取中间2个其中任何一个作为中间元素
二分法检索是一种效率较高的检索方法,要求字典在顺序表中按关键码排序。
看代码
public class ArrayStructures { private int[] theArray = new int[50]; private int arraySize = 10; public void generateRandomArray(){ for (int i =0; i< arraySize;i++){ theArray[i] = (int)(Math.random()*10 + 10); } } public void printArray(){ StringBuffer sb = new StringBuffer("-"); for (int i = 0; i<arraySize; i++){ sb.append("-----"); } String septalLine= sb.toString(); System.out.println(septalLine); for (int i = 0; i<arraySize; i++){ System.out.print("| " + i + " "); } System.out.println("|"); System.out.println(septalLine); for (int i = 0; i<arraySize; i++){ System.out.print("| " + theArray[i] + " "); } System.out.println("|"); System.out.println(septalLine); } public void insertionSort(){ for(int i=1; i<arraySize; i++){ int j= i; int insertValue = theArray[i]; while (j>0 && theArray[j-1]>insertValue){ theArray[j]= theArray[j-1]; j--; } theArray[j]=insertValue; } } public void binarySearchForValue(int value){ int lowIndex = 0; int highIndex = arraySize -1; while(lowIndex<= highIndex){ int middleIndex = (lowIndex +highIndex)/2; if(theArray[middleIndex] < value) lowIndex = middleIndex + 1; else if(theArray[middleIndex] > value) highIndex = middleIndex - 1; else { System.out.println("The value " + value +" at Index " + middleIndex); return; } } System.out.println("The value " + value +" is not in this array"); } public static void main(String[] args) { // Generate an Array System.out.println("Create an array, and fill in random value"); ArrayStructures as = new ArrayStructures(); // Set Random value in Array as.generateRandomArray(); // Print original array as.printArray(); System.out.println(); System.out.println("Insertion Sort"); as.insertionSort(); as.printArray(); System.out.println(); System.out.println("Binary Search"); as.binarySearchForValue(14); System.out.println(); } }
输出结果
Create an array, and fill in random value --------------------------------------------------- | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | --------------------------------------------------- | 11 | 12 | 13 | 14 | 18 | 14 | 19 | 11 | 17 | 19 | --------------------------------------------------- Insertion Sort --------------------------------------------------- | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | --------------------------------------------------- | 11 | 11 | 12 | 13 | 14 | 14 | 17 | 18 | 19 | 19 | --------------------------------------------------- Binary Search The value 14 at Index 4
本文出自 “10314466” 博客,请务必保留此出处http://10324466.blog.51cto.com/10314466/1659522
原文地址:http://10324466.blog.51cto.com/10314466/1659522