问题描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
例如下面的二维数组就是每行、每列都递增排序。如果在这个数组中查找数字6,则返回true;如果查找数字5,由于数组不含有该数字,则返回false。
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
杨氏矩阵的二分查找:
首先直接定位到最右上角的元素,如果比要找的数(6)大,则往左走,
如果比要找的数(6)小,则往下走,直到找到要找的数为止。
代码实现:
#include <iostream> using namespace std; /* * desc:杨氏矩阵二分查找 * author: chenwq ([email protected]) && July * version: 1.0 2012/05/22 */ #define ROW 4 #define COL 4 bool Young(int array[][COL], int search){ int i = 0; int j = COL - 1; int var = array[i][j]; while(true){ if(var == search) return true; else if(var < search && i < ROW - 1){ var = array[++i][j]; cout << "smaller " << var << "\n"; } else if(var > search && j > 0){ var = array[i][--j]; cout << "larger " << var << "\n"; } else return false; } } int main(){ int array[ROW][COL] = { {1, 2, 8, 9} ,{2, 4, 9 ,12} ,{4, 7, 10, 13} ,{6, 8, 11, 16} }; Young(array, 6); /* for(int search = 1; search <= 15; search++){ cout << search << "\n"; if(Young(array, search)) cout << "exists" << "\n"; else cout << "not exists" << "\n"; } */ return 0; }