对一个行列都是升序的二维数组中查找一个数字

    xiaoxiao2025-02-06  23

    <table border="1" width="200" cellspacing="1" cellpadding="1"><tbody><tr><td>0</td><td>3</td><td>6</td><td>10</td></tr><tr><td>2</td><td>5</td><td>9</td><td>11</td></tr><tr><td>5</td><td>7</td><td>10</td><td>13</td></tr><tr><td>6</td><td>8</td><td>14</td><td>18</td></tr></tbody></table><pre name="code" class="cpp"><span style="font-size:18px;">#include <iostream> using namespace std; bool Find(int* arr, int rows, int columns, int key)//传值要将行列都传进来 { bool sign = false;//定义一个标志 if (arr != NULL && rows > 0 && columns > 0) { int row = 0; int column = columns - 1; while (row < rows &&column >= 0)//从右上角开始查找 { if (arr[row*columns + column] == key) { sign = true; break; } else if (arr[row*columns + column] < key)//小于key,向下一行查找 { row++; } else { column--; //大于key,向前一列查找 } } } return sign; } int main() { int arr[][4] = { { 0, 3, 6, 10 }, { 2, 5, 9, 11 }, { 5, 7, 10, 13 }, { 6, 8, 14, 18 } }; bool ret1 = Find((int*)arr, 4, 4, 7);//将二级指针强转为一级指针 cout << "ret1=" << ret1 << endl; bool ret2 = Find((int*)arr, 4, 4, 100); cout << "ret2=" << ret2 << endl; bool ret3 = Find((int*)arr, 4, 4, 6); cout << "ret3=" << ret3 << endl; bool ret4 = Find((int*)arr, 4, 4, 6); cout << "ret4=" << ret4 << endl; system("pause"); return 0; }</span> 在写这个代码的时候出现的问题:函数传二级指针时,开始直接传的(int**)arr类型,发现不可以这样传,然后强转为(int*)arr,再传入行数和列数。

    转载请注明原文地址: https://ju.6miu.com/read-1296142.html
    最新回复(0)