Given that the binary search algorithm we recently saw on the Internet is very complex and has too many details and is not easy to understand, the following provides several simple and easy-to-understand code templates.
First, let's remember the most basic binary search template:
Search for the key in the ordered array A. If the key is found, the location index is returned. Otherwise,-1 is returned;
int BinarySearch(int A[], int n, int key){ int left = 0, right = n - 1; while (left <= right) { int mid = left + (right - left) / 2; if (A[mid] < key) { left = mid + 1; } else if (A[mid] > key) { right = mid - 1; } else {// A[mid] == key return mid; } } return -1;}
Variant 1: If a has multiple key elements, the maximum value is returned. Otherwise,-1 is returned.
Int binarysearch (int A [], int N, int key) {int left = 0, Right = n-1; int result =-1; while (left <= right) {int mid = left + (right-left)/2; if (a [Mid] <key) {left = Mid + 1 ;} else if (a [Mid]> key) {right = mid-1;} else {// A [Mid] = Key Result = mid; left = Mid + 1; // continue searching for the right half.} return result ;}
Variant 2: If a contains multiple key elements, return the smallest value. Otherwise, return-1.
Int binarysearch (int A [], int N, int key) {int left = 0, Right = n-1; int result =-1; while (left <= right) {int mid = left + (right-left)/2; if (a [Mid] <key) {left = Mid + 1 ;} else if (a [Mid]> key) {right = mid-1;} else {// A [Mid] = Key Result = mid; Right = mid-1; // continue searching for the left half.} return result ;}
Variant 3: In the ordered array A, find the smallest element index that is greater than the key.
int BinarySearch(int A[], int n, int key){ if (A[n-1] < key) return -1; int left = 0, right = n - 1; while (left != right) { int mid = left + (right - left) / 2; if (A[mid] <= key) { left = mid + 1; } else { right = mid; } } return left;}
Variant 4: Find the largest element index smaller than K in the ordered array.
int BinarySearch(int A[], int n, int key){ if (A[0] > key) return -1; int left = 0, right = n - 1; while (left < right-1) { int mid = left + (right - left) / 2; if (A[mid] >= key) { right = mid - 1; } else { left = mid; } } if (A[right] < key) { return right; } else { return left; }}
Binary Search and its variants are easy to understand templates