杨氏矩阵的查找【二维数组中数据的查找】

来源:互联网 发布:手机怎样添加网络 编辑:程序博客网 时间:2024/06/05 19:00

什么是杨氏矩阵就不再赘述,自己网查。

代码实现:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <errno.h>int find(int *arr, int rows, int cols, int num,int *rrow,int *rcol){//rows 行//cols 列int row = 0;int col = cols - 1;int ret = 0;if (arr != NULL&& rows > 0 && cols > 0){while (row < rows && col >= 0){if (num == arr[row * cols + col])//找到{ret = 1;*rrow = row;*rcol = col;break;}else if (num < arr[row * cols + col])//去掉右边的列{col--;}else{row++;//去掉上边的行}}}return ret;}int main(){int ret = -1;int col=-1, row=-1;int arr[][3] = { { 1, 2, 3 }, { 3, 4, 5 }, { 6, 7, 8 } };ret = find(&arr[0][0], 3, 3, 8,&row,&col);printf("find = %d,row = %d,col = %d\n", ret,row,col);ret = find(&arr[0][0], 3, 3, 1, &row, &col);printf("find = %d,row = %d,col = %d\n", ret, row, col);ret = find(&arr[0][0], 3, 3, 5, &row, &col);printf("find = %d,row = %d,col = %d\n", ret, row, col);ret = find(&arr[0][0], 3, 3, 10, &row, &col);printf("find = %d,row = %d,col = %d\n", ret, row, col);getchar();return 0;}
环境VS2013.

测试结果:


0 0