mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-07 06:44:57 +08:00
[Rust] Normalize mid calculation in case overflow (#1363)
* Normalize mid calculate in case overflow * Change ALL language * Update merge_sort.py * Update merge_sort.zig * Update binary_search_tree.zig * Update binary_search_recur.py --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
@ -12,7 +12,7 @@ def binary_search(nums: list[int], target: int) -> int:
|
||||
# Loop until the search interval is empty (when i > j, it is empty)
|
||||
while i <= j:
|
||||
# Theoretically, Python's numbers can be infinitely large (depending on memory size), so there is no need to consider large number overflow
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
m = i + (j - i) // 2 # Calculate midpoint index m
|
||||
if nums[m] < target:
|
||||
i = m + 1 # This situation indicates that target is in the interval [m+1, j]
|
||||
elif nums[m] > target:
|
||||
@ -28,7 +28,7 @@ def binary_search_lcro(nums: list[int], target: int) -> int:
|
||||
i, j = 0, len(nums)
|
||||
# Loop until the search interval is empty (when i = j, it is empty)
|
||||
while i < j:
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
m = i + (j - i) // 2 # Calculate midpoint index m
|
||||
if nums[m] < target:
|
||||
i = m + 1 # This situation indicates that target is in the interval [m+1, j)
|
||||
elif nums[m] > target:
|
||||
|
@ -9,7 +9,7 @@ def binary_search_insertion_simple(nums: list[int], target: int) -> int:
|
||||
"""Binary search for insertion point (no duplicate elements)"""
|
||||
i, j = 0, len(nums) - 1 # Initialize double closed interval [0, n-1]
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
m = i + (j - i) // 2 # Calculate midpoint index m
|
||||
if nums[m] < target:
|
||||
i = m + 1 # Target is in interval [m+1, j]
|
||||
elif nums[m] > target:
|
||||
@ -24,7 +24,7 @@ def binary_search_insertion(nums: list[int], target: int) -> int:
|
||||
"""Binary search for insertion point (with duplicate elements)"""
|
||||
i, j = 0, len(nums) - 1 # Initialize double closed interval [0, n-1]
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
m = i + (j - i) // 2 # Calculate midpoint index m
|
||||
if nums[m] < target:
|
||||
i = m + 1 # Target is in interval [m+1, j]
|
||||
elif nums[m] > target:
|
||||
|
@ -41,7 +41,7 @@ def merge_sort(nums: list[int], left: int, right: int):
|
||||
if left >= right:
|
||||
return # Terminate recursion when subarray length is 1
|
||||
# Partition stage
|
||||
mid = (left + right) // 2 # Calculate midpoint
|
||||
mid = left + (right - left) // 2 # Calculate midpoint
|
||||
merge_sort(nums, left, mid) # Recursively process the left subarray
|
||||
merge_sort(nums, mid + 1, right) # Recursively process the right subarray
|
||||
# Merge stage
|
||||
|
Reference in New Issue
Block a user