From 62eef0886f5eb2937db8cac775f2ab637ee55e85 Mon Sep 17 00:00:00 2001 From: Priyanshu Singh <123263608+dev-priyanshu15@users.noreply.github.com> Date: Sat, 12 Oct 2024 15:14:38 +0530 Subject: [PATCH] Create Staircase Search in a 2D Matrix --- search/Staircase Search in a 2D Matrix | 35 ++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 search/Staircase Search in a 2D Matrix diff --git a/search/Staircase Search in a 2D Matrix b/search/Staircase Search in a 2D Matrix new file mode 100644 index 00000000000..1b1193caad1 --- /dev/null +++ b/search/Staircase Search in a 2D Matrix @@ -0,0 +1,35 @@ +#include +using namespace std; + +bool staircaseSearch(vector>& matrix, int target) { + int rows = matrix.size(); + int cols = matrix[0].size(); + int row = 0, col = cols - 1; + + while (row < rows && col >= 0) { + if (matrix[row][col] == target) { + return true; + } else if (matrix[row][col] > target) { + col--; + } else { + row++; + } + } + return false; +} + +int main() { + vector> matrix = { + {1, 4, 7, 11}, + {2, 5, 8, 12}, + {3, 6, 9, 16}, + {10, 13, 14, 17} + }; + int target = 8; + if (staircaseSearch(matrix, target)) + cout << "Element found." << endl; + else + cout << "Element not found." << endl; + + return 0; +}