数组:
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 search(int arr[3][3], int a, int row, int col){
int x = 0;
int y = col - 1;
//利用杨氏矩阵特性,让k每次与右上角的数比较,行向下逼近,列向左逼近,直到查找到左下角的数,如果还不相等,直接返回0;说明没找到
while ((x < row) && (y >= 0)){
if (a > arr[x][y]){
x++;
}
else if (a == arr[x][y]){
return 1;
}
else{
y--;
}
}
return 0;
}
int main()
{
int arr[3][3] = { 1,2,3,4,5,6,7,8,9 };
int key = 5;
int result = 0;
result = search(arr, key, 3, 3);//封装一个函数,利用函数的返回值来判定是否找到
if (result==1){
printf("找到了\n");
}
else{
printf("找不到\n");
}
return 0;
system("pause");
}