|
| 1 | +def binary_search(array: list, lower_bound: int, upper_bound: int, value: int) -> int: |
| 2 | + """ |
| 3 | + This function carries out Binary search on a 1d array and |
| 4 | + return -1 if it do not exist |
| 5 | + array: A 1d sorted array |
| 6 | + value : the value meant to be searched |
| 7 | + >>> matrix = [1, 4, 7, 11, 15] |
| 8 | + >>> binary_search(matrix, 0, len(matrix) - 1, 1) |
| 9 | + 0 |
| 10 | + >>> binary_search(matrix, 0, len(matrix) - 1, 23) |
| 11 | + -1 |
| 12 | + """ |
| 13 | + |
| 14 | + r = int((lower_bound + upper_bound) // 2) |
| 15 | + if array[r] == value: |
| 16 | + return r |
| 17 | + if lower_bound >= upper_bound: |
| 18 | + return -1 |
| 19 | + if array[r] < value: |
| 20 | + return binary_search(array, r + 1, upper_bound, value) |
| 21 | + else: |
| 22 | + return binary_search(array, lower_bound, r - 1, value) |
| 23 | + |
| 24 | + |
| 25 | +def mat_bin_search(value: int, matrix: list) -> list: |
| 26 | + """ |
| 27 | + This function loops over a 2d matrix and calls binarySearch on |
| 28 | + the selected 1d array and returns [-1, -1] is it do not exist |
| 29 | + value : value meant to be searched |
| 30 | + matrix = a sorted 2d matrix |
| 31 | + >>> matrix = [[1, 4, 7, 11, 15], |
| 32 | + ... [2, 5, 8, 12, 19], |
| 33 | + ... [3, 6, 9, 16, 22], |
| 34 | + ... [10, 13, 14, 17, 24], |
| 35 | + ... [18, 21, 23, 26, 30]] |
| 36 | + >>> target = 1 |
| 37 | + >>> mat_bin_search(target, matrix) |
| 38 | + [0, 0] |
| 39 | + >>> target = 34 |
| 40 | + >>> mat_bin_search(target, matrix) |
| 41 | + [-1, -1] |
| 42 | + """ |
| 43 | + index = 0 |
| 44 | + if matrix[index][0] == value: |
| 45 | + return [index, 0] |
| 46 | + while index < len(matrix) and matrix[index][0] < value: |
| 47 | + r = binary_search(matrix[index], 0, len(matrix[index]) - 1, value) |
| 48 | + if r != -1: |
| 49 | + return [index, r] |
| 50 | + index += 1 |
| 51 | + return [-1, -1] |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + import doctest |
| 56 | + |
| 57 | + doctest.testmod() |
0 commit comments