Skip to content

Commit 56ff577

Browse files
committed
Staircase search algo for sorted 2-d arrays
1 parent 0bd8b46 commit 56ff577

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Staircase Search/staircaseSearch.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/* Searches the element x in mat[][]. If the
2+
element is found, then prints its position
3+
and returns true, otherwise prints "not found"
4+
and returns false */
5+
int search(int mat[4][4], int n, int x)
6+
{
7+
if (n == 0)
8+
return -1;
9+
int smallest = a[0][0], largest = a[n - 1][n - 1];
10+
if (x < smallest || x > largest)
11+
return -1;
12+
// set indexes for top right element
13+
int i = 0, j = n - 1;
14+
while (i < n && j >= 0) {
15+
if (mat[i][j] == x) {
16+
cout << "n Found at "
17+
<< i << ", " << j;
18+
return 1;
19+
}
20+
if (mat[i][j] > x)
21+
j--;
22+
else // if mat[i][j] < x
23+
i++;
24+
}
25+
26+
cout << "n Element not found";
27+
return 0; // if ( i==n || j== -1 )
28+
}
29+
30+
// Driver code
31+
int main()
32+
{
33+
int mat[4][4] = { { 10, 20, 30, 40 },
34+
{ 15, 25, 35, 45 },
35+
{ 27, 29, 37, 48 },
36+
{ 32, 33, 39, 50 } };
37+
search(mat, 4, 29);
38+
39+
return 0;
40+
}

0 commit comments

Comments
 (0)