Skip to content

Commit f435d43

Browse files
authored
Merge pull request keon#47 from ankit167/Search_in_a_sorted_matrix
Added code to search in a row wise and column wise sorted matrix.
2 parents 122da95 + aa25d45 commit f435d43

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

matrix/search_in_sorted_matrix.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#
2+
# Search a key in a row wise and column wise sorted (non-decreasing) matrix.
3+
# m- Number of rows in the matrix
4+
# n- Number of columns in the matrix
5+
# T(n)- O(m+n)
6+
#
7+
8+
9+
def search_in_a_sorted_matrix(mat, m, n, key):
10+
i, j = m-1, 0
11+
while i >= 0 and j < n:
12+
if key == mat[i][j]:
13+
print ('Key %s found at row- %s column- %s' % (key, i+1, j+1))
14+
return
15+
if key < mat[i][j]:
16+
i -= 1
17+
else:
18+
j += 1
19+
print ('Key %s not found' % (key))
20+
21+
22+
def main():
23+
mat = [
24+
[2, 5, 7],
25+
[4, 8, 13],
26+
[9, 11, 15],
27+
[12, 17, 20]
28+
]
29+
key = 13
30+
print (mat)
31+
search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), key)
32+
33+
34+
if __name__ == '__main__':
35+
main()

0 commit comments

Comments
 (0)