First of all, the binary search method.
Binary search method is to find a set of ordered numbers, pass the corresponding data, compare to find the same data as the original data, find the return 1, failed to return the corresponding array subscript.
The two-point search method was completed by non-recursive method. The Java code is shown below.
[Java]View PlainCopyprint?
- /*
- * Non-recursive binary search algorithm
- * Parameter: integer array, the number to compare.
- */
- public static int BinarySearch (integer[]srcarray,int des) {
- //First position.
- int low=0;
- //Highest position. Array Length-1, since the subscript is starting from 0.
- int high=srcarray.length-1;
- //When Low "pointer" and high do not repeat.
- While (Low<=high) {
- //Middle position calculation, low+ the highest position minus the lowest position, move right one bit, equivalent to 2. can also be used (High+low)/2
- int middle=low+ ((high-low) >>1);
- and//with the most intermediate numbers to determine whether they are equal or equal, the corresponding array subscripts are returned.
- if (Des==srcarray[middle]) {
- return middle;
- //If less then move the "pointer" at the top level
- }Else if (Des<srcarray[middle]) {
- high=middle-1;
- //Move the lowest "pointer"
- }else{
- Low=middle+1;
- }
- }
- return-1;
- }
- }
Recursive method is used to complete the two-point search algorithm. The code is shown below.
[Java]View PlainCopy print?
- /**
- * Recursive method to realize the binary search method.
- * @param array arrays
- * @param low Array First position
- * @param high
- * @param key to find the value.
- * @return return value.
- */
- int Binsearch (int array[],int low,int high,int key)
- {
- if (Low<=high)
- {
- int mid = (Low+high)/2;
- if (key = = Array[mid])
- return mid;
- Else if (Key<array[mid])
- //Move low and high
- return Binsearch (array,low,mid-1,key);
- Else if (Key>array[mid])
- return Binsearch (array,mid+1,high,key);
- }
- Else
- return-1;
- }
Recursive thinking is often used, more prominent programming problem-solving efficiency.
Excerpt from: http://blog.csdn.net/lovesummerforever/article/details/24588989
Binary lookup algorithm (recursive vs. non-recursive two ways)