杨氏矩阵
有一个二维数组,数组的每行从左到右是递增的,每列从上到下是递增的,在这样的数组中查找一个数字是否存在。
时间复杂度小于O(N);
数组:
1 2 3
2 3 4
3 4 5
1 3 4
2 4 5
4 5 6
1 2 3
4 5 6
7 8 9
#include<stdio.h>
#include<stdlib.h>
int Find_array(int(*arr)[3], int to_find,int rows,int columns) {
int row = 0;
int column = columns - 1;
while(column >= 0 && row < rows) {
if (arr[row][column] == to_find) {
return 1;
}
else if (arr[row][column] < to_find) {
row++;
}
else {
column--;
}
}
return 0;
}
int main() {
int arr[3][3] = { {1,2,3} ,{4,5,6}, {7,8,9} };
int to_find = 0;
int rows = 3;
int columns = 3;
printf("请输入一个数:");
scanf("%d", &to_find);
Find_array(arr, to_find,rows,columns);
if (Find_array(arr, to_find, rows, columns)) {
printf("找到了!\n");
}
else {
printf("没找到!\n");
}
system("pause");
return 0;
}