This article brings you the content is about Java Lookup instance: Binary method to find the elements of the Method (code), there is a certain reference value, the need for friends can refer to, I hope to help you.
Two-part method to find the principle of thinking:
Search Data and ordered Array The intermediate element is compared to determine whether the middle element is left or right, if it is on the right, the minimum search index value is adjusted, then the next loop is adjusted, if it is on the left, the maximum search index value is resized, then the next loop is reached, and if the current position is the location of the lookup data, stop the loop;
Attention:
Because the element is found based on the size relationship between the elements of the array, the array must be an ordered array, and the code in ascending (small to large) and descending (large to small) will be different. This article takes ascending order as an example.
public class dichotomy {public static void main (string[] args) { int [] array = {1,2,3,4,5}; int target = 2;//= array[1] int low = 0;int High = array.length-1;while (Low <= high) { int middle = (low + hi) GH)/2; if (Target > Array[middle]) {Low = middle + 1, } else if (Target < Array[middle]) {High = middle-1;< c8/>} else { System.out.println (middle); Break;}}}}
The following is the result of the operation:
If an unordered array is used to find an element by means of a dichotomy, sort the array first. For example, use the bubble sort method to sort ascending (small to large).
Below is the specific code:
public class dichotomy {public static void main (string[] args) { int [] array = {3,2,5,1,4}; Sort int temp = 0;for (int time = 1; time < Array.Length; time++) {for (int i = 0; i < array.length-time; i++) { if (Array[i+1]<array[i]) {temp = array[i+1];array[i+1] = array[i];array[i] = temp;}}} for (int i = 0; i < Array.Length; i++) {System.out.println (array[i]);} Binary lookup int target = 2;//= array[1] int low = 0; int high = array.length-1; while (low <= high) { int middle = (low + high)/2; if (Target > Array[middle]) {Low = middle + 1, } else if (Target < Array[middle]) {High = middle- 1; } else { System.out.println (middle); Break;}}}}
The following is the result of the operation: