這個答案不是我想出來的,而是看的書上的,然後我把答案默寫出來了,不過改成c語言下可以正確運行的了,令我沒想到的是c語言竟然沒有bool類型,結果代碼一直出錯。
這裏面也用到了這樣一個知識點:在C/C++中,當數組作爲函數的參數進行傳遞時,數組就自動退化爲同類型的指針。
#include <stdio.h>
typedef int bool;
#define true 1
#define false 0
bool search(int *matrix, int rows, int columns, int number)
{
bool found = false;
int row = 0;
int column = columns - 1;
if(matrix != NULL && rows > 0 && columns > 0)
{
while(row < rows && column >= 0)
{
if(matrix[row * columns + column] == number)
{
found = true;
break;
}else if(matrix[row * columns + column] > number)
{
column--;
}else if(matrix[row * columns + column] < number)
{
row++;
}
}
}
return found;
}
void main()
{
int test[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
if(search((int *)test, 4, 4, 11) == true)
{
printf("要找的數在數組中\n");
}else
{
printf("要找的數不在數組中\n");
}
}