Binary Search:
It is very simple, but do not take it lightly. So, write it down, just in case:
int binary_search(int* a, int low, int high, int Num){if(low > high)return -1;int middle = (low + high)/2;if(Num == a[middle])return middle;else if(Num > a[middle])binary_search(a, middle + 1, high, Num);elsebinary_search(a, low, middle - 1, Num);}
Young's matrix query problem: in a two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, input a two-dimensional array and an integer to determine whether the array contains the integer. For example, the following two-dimensional array is the incremental sorting of each row and column. If the number 6 is searched in this array, true is returned. If the number 5 is searched, false is returned because the array does not contain this number. I directly implemented method 2. First, I directly located the element in the top-right corner and matched it with a binary search. I went to the left when it was larger than the number (6) I was looking, if you want to find a small number (6), go down until you find the number (6), as shown in: // code
#define COL 4#define ROW 4bool young_matrix_search(int array[][COL], int Num){int i = 0, j = COL-1;while(i >= 0 && i <= ROW - 1 && j >= 0 && j <= COL - 1){if(array[i][j] == Num)return true;if(array[i][j] > Num)j--;if(array[i][j] < Num)i++;}return false;}#include <iostream>using namespace std;int main(){//int a[] = {1,3,5,7,9,12,45};//binary_search(a, 0, sizeof(a)/sizeof(a[0]) - 1, 55);int a[ROW][COL] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};for (int i = 1; i <= 15; i++){if (young_matrix_search(a, i))cout<<"search:"<<i<<" hit!"<<endl;elsecout<<"search:"<<i<<" miss!"<<endl;}}