在一個二維陣列中,每一行都按照從左到右遞增的順序排列,每一列都按照從上到下遞增的順序排列,請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。
阿新 • • 發佈:2019-01-07
c++程式碼
#include<iostream> #include<iomanip> using namespace std; void find(int *matrix, int rows, int cols, int k) { if (matrix != NULL&&rows > 0 && cols > 0) { int row = 0; int result = 0; int col = cols - 1; while (row < rows&&col >= 0) { if (matrix[row*cols + col] == k) { cout << "在二維陣列的第" << row+1 << "行" << col+1 << "列" << endl;//右上角的數 result = 1; break; } else if (matrix[row*cols + col]> k) col--; else row++; } if (result == 0) cout << "未在陣列中找到" << endl; } } int main() { int k;//k為要查詢的數 bool result; int matrix[4][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; cout << "輸入的矩陣為" << endl; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { cout <<setw(3)<< matrix[i][j] << " "; } cout << endl; } cout << "請輸入要查詢的數" << endl; cin >> k; find((int*)matrix, 4, 4, k);//注意呼叫方式 system("pause"); return 0; }
執行結果