First of all, the binary search method.
The binary search method is to find a set of ordered numbers, pass the corresponding data, compare and find the same data as the original data, and find the corresponding array subscript, no return 1 is found;
The following example, in which ordered arrays are arranged in small to large order. (Thanks again to the Netizen's point)
The two-point search method was completed by non-recursive method. The Java code is shown below.
/**
* Two points to find common implementations.
* @param srcarray ordered array
* @param key Find element
* @return not present return-1
*
/public static int Binsearch (int sr carray[], int key) {
int mid;
int start = 0;
int end = Srcarray.length-1;
while (start <= end) {
mid = (End-start)/2 + start;
if (Key < Srcarray[mid]) {
end = mid-1;
} else if (Key > Srcarray[mid]) {
start = mid + 1;
} E LSE {
return mid;
}
}
return-1;
}
Recursive method is used to complete the two-point search algorithm. The code is shown below.
/**
* Binary search recursive implementation.
* @param srcarray ordered array
* @param start array low address subscript
* @param end Array High address subscript
* @param key find element
* @return Lookup element does not exist return-1
*
/public static int binsearch (int srcarray[], int start, int end, int key) {
int mid = (End-start)/2 + start;
if (srcarray[mid] = = key) {
return mid;
}
if (start >= end) {
return-1;
} else if (Key > Srcarray[mid]) {
return Binsearch (Srcarray, mid + 1, End, key);
} else if (Key < Srcarray[mid]) {
return Binsearch (Srcarray, start, mid-1, key);
}
return-1;
}
Recursive thinking is often used, more prominent programming problem-solving efficiency.
The call executes the main function, and the code is as follows.
public static void Main (string[] args) {
int srcarray[] = {3,5,11,17,21,23,28,30,32,50,64,78,81,95,101};
System.out.println (Binsearch (srcarray, 0, Srcarray.length-1, 222));
System.out.println (Binsearch (srcarray,81));
}
Say sorry here, before the code has a problem, oneself has been without modification, sin sin