0904 _ two small questions _ binary search and Young's matrix search

Source: Internet
Author: User

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;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.