The example of this article tells the two -point search algorithm of Java. Share it for everyone for your reference. The specifics are as follows:
1. Prerequisite: The premise of the two -point search is that the array that needs to be found must be sorted.
2. Principles: Divide the number into three parts, in order, before the median value (the so -called median is the value of the middle position of the array). Smaller is found in front of the median value. Then in turn, the recursive process will continue to decompose the first half or the second half into three parts. It may not be clearly described. If you don't understand, you can go online. From the description, it can be seen that this algorithm is suitable for recursion, and those who are recursion can be implemented with cycles. Therefore, our implementation is divided into two types: recursion and cycle. You can understand the algorithm according to the code
Implement code:
public class binarysearch {public static void main (string [] art) {int Searcharrrrrrr [] = New Int [1000000]; for (int i = 0; i <1000000) {searcharrrrrrrrrrrrrrr [i] = i ;} System. Out.println (binsearch (searcharrrrrr, 0, searcharr.Length-99)); System.out.println (Binsearch (Search (99)); t 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;} // Cycle two points Find the Public Static Int Binsearch (int ARR [], int key) {int Mid = Arrr.Length/2; int Start = 0; int End = Arrr.Length -; 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 cycle duplex search algorithm is higher than the recursive dual -point search algorithm
It is hoped that this article is helpful to everyone's Java program design.