二维数组中的查找

题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

思路:这题和堆排序有类似,查找过程中从右上方的数字开始,如果该数字比查找的数字小,那么该数字所在行可以删除,不用继续考虑;如果该数字比查找的数字大,那么该数字所在列可以删除。这样,每次执行,都会删除一行或者一列,极端情况下,执行2n次。

 1 #include "stdafx.h"
 2 #include<stdio.h>
 3 
 4 bool Find(int* matrix, int rows, int columns, int number)
 5 {
 6     bool found = false;
 7 
 8     if(matrix != NULL && rows > 0 && columns > 0)
 9     {
10         int row = 0;
11         int column = columns - 1;
12         while(row < rows && column >= 0)
13         {
14             if(matrix[row*columns + column] == number)
15             {
16                 found = true;
17                 printf("the number %d is in row: %d and column: %d
", number, row+1, column +1);
18                 break;
19             }
20             else if(matrix[row*columns + column] > number)
21                 -- column;
22             else
23                 ++ row;
24         }
25     }
26 
27     return found;
28 }
29 
30 void Test(char* testName, int* matrix, int rows, int columns, int number, bool expected)
31 {
32     if(testName != NULL)
33         printf("%s begins.
", testName);
34 
35     bool result = Find(matrix, rows, columns, number);
36     if(result == expected)
37         printf("Passed.
");
38     else
39         printf("Failed.
");
40 }
41 
42 void Test1()
43 {
44     int matrix[][4] = {{1,2,8,9}, {2,4,9,12},{4,7,10,13},{6,8,11,15}};
45     Test("Test1", (int*)matrix, 4,4,7,true);
46 }
47 
48 // 1   2   8    9
49 // 2   4   9   12
50 // 4   7   10  13
51 // 6   8   11  15
52 int main()
53 {
54     int rows = 4;
55     int columns = 4;
56     int number = 7;
57     int matrix[][4] = {{1,2,8,9}, {2,4,9,12},{4,7,10,13},{6,8,11,15}};
58     
59     for(int i = 0 ; i < rows; i++)
60     {
61         for(int j = 0 ;j < columns; j++)
62             printf("%d	", matrix[i][j]);
63         
64         printf("
");
65     }
66     printf("
");
67     bool result = Find((int*)matrix, rows, columns, number);
68     if(result)
69         printf("found.
");
70     else
71         printf("not found.
");
72     
73     return 0;
74 }

原文地址:https://www.cnblogs.com/sankexin/p/5643821.html