Skip to content

Commit 3da098b

Browse files
authored
Update BinarySearch_on_Sorted_2D_Array.py
1 parent 5afd15a commit 3da098b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
def binary_search_2d(matrix: list[list[int]], target: int) -> tuple[int, int]:
2+
"""
3+
Searches for a target value in a 2D sorted array.
4+
5+
The matrix is sorted such that each row is in ascending order, and the
6+
first element of each row is greater than the last element of the previous row.
7+
8+
:param matrix: A 2D list of integers sorted in ascending order.
9+
:param target: The integer value to search for.
10+
:return: A tuple (row_index, col_index) if found, otherwise (-1, -1).
11+
12+
Examples:
13+
>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 9)
14+
(1, 1)
15+
>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 4)
16+
(-1, -1)
17+
"""
18+
if not matrix or not matrix[0]:
19+
return -1, -1
20+
21+
rows, cols = len(matrix), len(matrix[0])
22+
left, right = 0, rows * cols - 1
23+
24+
while left <= right:
25+
mid = left + (right - left) // 2
26+
mid_value = matrix[mid // cols][mid % cols]
27+
28+
if mid_value == target:
29+
return mid // cols, mid % cols
30+
elif mid_value < target:
31+
left = mid + 1
32+
else:
33+
right = mid - 1
34+
35+
return -1, -1
36+
37+
38+
if __name__ == "__main__":
39+
import doctest
40+
41+
doctest.testmod()
42+
43+
# Example usage
44+
matrix = [[1, 3, 5], [7, 9, 11], [12, 13, 15]]
45+
target = 9
46+
result = binary_search_2d(matrix, target)
47+
if result == (-1, -1):
48+
print(f"{target} was not found in the matrix.")
49+
else:
50+
print(f"{target} was found at position {result} in the matrix.")

0 commit comments

Comments
 (0)