This article describes the Java implementation of the binary lookup algorithm. Share to everyone for your reference. Specifically as follows:
1. Prerequisite: The premise of the binary lookup is the need to find the array must be sorted, our implementation here defaults to ascending
2. Principle: The array is divided into three parts, followed by the median (the so-called median is the value of the middle of the array) before the median, the median value of the value to be looked for and the value of the group, if less than the median is found in front of the median value, if the value is greater than the median is found after the median, equal to the median when directly returned. Then there is a recursive process, which continues to decompose the first half or the second half into three parts. May be described is not very clear, if not understand can go online to find. It can be seen from the description that this algorithm is suitable for the recursive implementation, can be used recursively can be implemented with the loop. So our implementation is divided into recursion and loop, can be based on the code to understand the algorithm
Implementation code:
public class BinarySearch {public static void main (string[] args) {int searcharr[] = new int[1000000];
for (int i=0;i<1000000;i++) {searcharr[i]=i;
} System.out.println (Binsearch (searcharr,0,searcharr.length-1,99));
System.out.println (Binsearch (searcharr,99));
///Recursive binary lookup public static int binsearch (int arr[], int start,int end,int sear) {int mid = (End-start)/2 + start;
if (Sear==arr[mid]) {return mid;
} if (start>=end) {return-1;
}else if (Sear < Arr[mid]) {return binsearch (arr,0,mid-1,sear);
}else if (Sear >arr[mid]) {return binsearch (arr,mid+1,end,sear);
} return-1;
///Loop binary lookup public static int binsearch (int arr[],int key) {int mid = ARR.LENGTH/2;
int start = 0;
int end = Arr.length-1;
while (start<=end) {mid = (End-start)/2+start;
if (key ==arr[mid]) {return mid;
}else if (key <= Arr[mid]) {end = Mid-1;
}else if (key >=arr[mid]) { start = mid+1;
}} return-1;
}
Efficiency comparison:
The efficiency of the cyclic binary lookup algorithm is higher than the recursive binary lookup algorithm
I hope this article will help you with your Java programming.