mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-25 10:28:39 +00:00
Update and rename BinarySearch_on_Sorted_2D_Array.py to binarysearch_on_sorted_2d_array.py
This commit is contained in:
parent
3da098ba6f
commit
c0b6798952
@ -1,3 +1,6 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
|
||||||
def binary_search_2d(matrix: list[list[int]], target: int) -> tuple[int, int]:
|
def binary_search_2d(matrix: list[list[int]], target: int) -> tuple[int, int]:
|
||||||
"""
|
"""
|
||||||
Searches for a target value in a 2D sorted array.
|
Searches for a target value in a 2D sorted array.
|
||||||
@ -5,20 +8,39 @@ def binary_search_2d(matrix: list[list[int]], target: int) -> tuple[int, int]:
|
|||||||
The matrix is sorted such that each row is in ascending order, and the
|
The matrix is sorted such that each row is in ascending order, and the
|
||||||
first element of each row is greater than the last element of the previous row.
|
first element of each row is greater than the last element of the previous row.
|
||||||
|
|
||||||
:param matrix: A 2D list of integers sorted in ascending order.
|
Args:
|
||||||
:param target: The integer value to search for.
|
matrix: A 2D list of integers sorted in ascending order.
|
||||||
:return: A tuple (row_index, col_index) if found, otherwise (-1, -1).
|
target: The integer value to search for.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A tuple (row_index, col_index) if found, otherwise (-1, -1).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If matrix is empty or not rectangular.
|
||||||
|
|
||||||
Examples:
|
|
||||||
>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 9)
|
>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 9)
|
||||||
(1, 1)
|
(1, 1)
|
||||||
>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 4)
|
>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 4)
|
||||||
(-1, -1)
|
(-1, -1)
|
||||||
|
>>> binary_search_2d([], 1) # doctest: +ELLIPSIS
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: matrix must not be empty
|
||||||
|
>>> binary_search_2d([[1, 2], [3, 4, 5]], 3) # doctest: +ELLIPSIS
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: matrix must be rectangular
|
||||||
"""
|
"""
|
||||||
if not matrix or not matrix[0]:
|
if not matrix or not matrix[0]:
|
||||||
return -1, -1
|
raise ValueError("matrix must not be empty")
|
||||||
|
|
||||||
|
rows = len(matrix)
|
||||||
|
cols = len(matrix[0])
|
||||||
|
|
||||||
|
for row in matrix:
|
||||||
|
if len(row) != cols:
|
||||||
|
raise ValueError("matrix must be rectangular")
|
||||||
|
|
||||||
rows, cols = len(matrix), len(matrix[0])
|
|
||||||
left, right = 0, rows * cols - 1
|
left, right = 0, rows * cols - 1
|
||||||
|
|
||||||
while left <= right:
|
while left <= right:
|
Loading…
x
Reference in New Issue
Block a user