Skip to content

Commit 18aa86b

Browse files
jiayang laiclaude
authored andcommitted
fix: improve code quality in searches and sorts
- binary_search.py: fix return type check in exponential_search (is None -> == -1) - linear_search.py: use ValueError instead of generic Exception - merge_sort.py: avoid O(n) pop(0) operations by using index-based merging Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 791deb4 commit 18aa86b

3 files changed

Lines changed: 13 additions & 6 deletions

File tree

searches/binary_search.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ def exponential_search(sorted_collection: list[int], item: int) -> int:
391391
last_result = binary_search_by_recursion(
392392
sorted_collection=sorted_collection, item=item, left=left, right=right
393393
)
394-
if last_result is None:
394+
if last_result == -1:
395395
return -1
396396
return last_result
397397

searches/linear_search.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int:
5555
-1
5656
"""
5757
if not (0 <= high < len(sequence) and 0 <= low < len(sequence)):
58-
raise Exception("Invalid upper or lower bound!")
58+
raise ValueError("Invalid upper or lower bound!")
5959
if high < low:
6060
return -1
6161
if sequence[low] == target:

sorts/merge_sort.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,17 @@ def merge(left: list, right: list) -> list:
3838
:return: Merged result
3939
"""
4040
result = []
41-
while left and right:
42-
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
43-
result.extend(left)
44-
result.extend(right)
41+
left_idx = 0
42+
right_idx = 0
43+
while left_idx < len(left) and right_idx < len(right):
44+
if left[left_idx] <= right[right_idx]:
45+
result.append(left[left_idx])
46+
left_idx += 1
47+
else:
48+
result.append(right[right_idx])
49+
right_idx += 1
50+
result.extend(left[left_idx:])
51+
result.extend(right[right_idx:])
4552
return result
4653

4754
if len(collection) <= 1:

0 commit comments

Comments
 (0)