diff --git a/Chapter 10 Sorting and searching/10.9. sorted_matrix_search.md b/Chapter 10 Sorting and searching/10.9. sorted_matrix_search.md new file mode 100644 index 0000000..18c3af3 --- /dev/null +++ b/Chapter 10 Sorting and searching/10.9. sorted_matrix_search.md @@ -0,0 +1,44 @@ +# 10.9. Sorted matrix search + +## Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element + +> example + +```python +A = [[1,2,4,5,7], + [2,3,5,6,8], + [3,6,7,8,10], + [4,7,8,9,11]] + +num = 3 +``` + +## First idea + +If A[0][3] < num and A[3][0] < num, if A[3][3] < num, return -1. Otherwise it must be in the matrix. + +If A[0][3] => num or A[3][0] => num, Iterate through the last column, find first row where `A[row][3] > num`. Then iterate that row from the back. If not found, iterate through the last row, do the same. This should take O(N+M) in the worst case. + +```python +def search_sorted_matrix(M, N, A, num): + if num < A[0][0] or num > A[M][N]: + return 0 + if num == A[0][0] or num == A[M][N]: + return 1 + if num < A[0][N]: + initidx = 0 + maxidx = N + while True: + i = maxidx // 2 + if A[0][i] == num: + return 1 + elif A[0][i] > num: + maxidx = i + elif A[0][i] < num: + initidx = i + + if A[0][initidx] < num and A[0][initidx+1] > num: + break + + +``` \ No newline at end of file diff --git a/Chapter 10 Sorting and searching/10.9. sorted_matrix_search.py b/Chapter 10 Sorting and searching/10.9. sorted_matrix_search.py new file mode 100644 index 0000000..e58d49f --- /dev/null +++ b/Chapter 10 Sorting and searching/10.9. sorted_matrix_search.py @@ -0,0 +1,44 @@ +import unittest + +M = 5 - 1 +N = 5 - 1 + +def search_sorted_matrix(A, num): + if num < A[0][0] or num > A[M][N]: + return 0 + if num == A[0][0] or num == A[M][N]: + return 1 + if num < A[0][N]: + initidx = 0 + maxidx = N + while True: + i = maxidx // 2 + if A[0][i] == num: + return 1 + elif A[0][i] > num: + maxidx = i + elif A[0][i] < num: + initidx = i + + if A[0][initidx] < num and A[0][initidx+1] > num: + break + return 0 + +class Test(unittest.TestCase): + data = [ + ([ + [0, 1, 3, 4, 6], + [6, 7, 8, 9, 10], + [11, 12, 13, 14, 15], + [16, 17, 18, 19, 20], + [21, 22, 23, 24, 25] + ], 2, 1) + ] + + def test_rotate_matrix(self): + for test_matrix, num, expected in self.data: + actual = search_sorted_matrix(test_matrix, num) + self.assertEqual(actual, expected) + +if __name__ == "__main__": + unittest.main() diff --git a/README.md b/README.md index 2f880dc..20caeb9 100644 --- a/README.md +++ b/README.md @@ -23,4 +23,8 @@ ## Chapter 8 Recursion -* Magic index \ No newline at end of file +* Magic index + +## Chapter 10 Sorting and searching + +* Sorted matrix search \ No newline at end of file