When it comes to search algorithms, the most classic is the binary search algorithm. In binary search, you need to find the target in the ordered data. First, compare the intermediate elements with the target,
When the target value is smaller than the intermediate element, the first half of the array is searched. If the target value is greater than the intermediate element, the second half of the array is obtained. Repeat the entire search process
Use the left half and half as the sub-array to continue searching until the element is found or the size of the sub-array is 0.
The principle is very simple, but there are many details, especially whether the value of the data boundary will cross the border, while loop conditions.
Java code:
Public class binarysearchdemo {private int search1 (INT [] A, int target) {int left = 0; int right =. length-1; int mid; while (left <= right) {mid = left + (right-left)> 1); if (a [Mid] <target) {left = Mid + 1;} else if (a [Mid]> Target) {right = mid-1;} elsereturn mid;} return-1 ;} public int search2 (INT [] A, int target) {int left = 0; int right =. length; // here, the array size has an impact on the subsequent while loop int mid; while (left <right) {mid = left + (right-left)> 1 ); if (target <A [Mid]) Right = mid; else if (target> A [Mid]) Left = Mid + 1; elsereturn mid;} return-1 ;} // implement the public int search3 (INT [] A, int left, int right, int target) {If (left> right) Return-1; int mid = left + (right-left)> 1); if (a [Mid] <target) {return search3 (A, Mid + 1, right, target);} else if (a [Mid]> Target) {return search3 (A, left, right-1, target);} else {return mid ;}} public static void main (string [] ARGs) {int A [] = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11 }; int target = 11; binarysearchdemo BS = new binarysearchdemo (); int pos1 = BS. search1 (A, target); system. out. println ("search1:" + pos1); int pos2 = BS. search2 (A, target); system. out. println ("search2:" + pos2); int pos3 = BS. search3 (A, 0,. length, target); system. out. println ("search3:" + pos3 );}}
Binary Search Algorithm