[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>
pull/1373/head
rongyi 6 months ago committed by GitHub
parent 0e221540a3
commit 21be3fdaf8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -43,7 +43,7 @@ void mergeSort(int *nums, int left, int right) {
if (left >= right)
return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

@ -39,7 +39,7 @@ void mergeSort(vector<int> &nums, int left, int right) {
if (left >= right)
return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

@ -39,7 +39,7 @@ public class merge_sort {
// 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
MergeSort(nums, left, mid); // 递归左子数组
MergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

@ -36,7 +36,7 @@ void mergeSort(List<int> nums, int left, int right) {
//
if (left >= right) return; // 1
//
int mid = (left + right) ~/ 2; //
int mid = left + (right - left) ~/ 2; //
mergeSort(nums, left, mid); //
mergeSort(nums, mid + 1, right); //
//

@ -46,7 +46,7 @@ func mergeSort(nums []int, left, right int) {
return
}
// 划分阶段
mid := (left + right) / 2
mid := left + (right - left) / 2
mergeSort(nums, left, mid)
mergeSort(nums, mid+1, right)
// 合并阶段

@ -42,7 +42,7 @@ public class merge_sort {
if (left >= right)
return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = (left + right) / 2; // 计算中点
int mid = left + (right - left) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

@ -39,7 +39,7 @@ function mergeSort(nums, left, right) {
// 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归
// 划分阶段
let mid = Math.floor((left + right) / 2); // 计算中点
let mid = Math.floor(left + (right - left) / 2); // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

@ -40,7 +40,7 @@ fun mergeSort(nums: IntArray, left: Int, right: Int) {
// 终止条件
if (left >= right) return // 当子数组长度为 1 时终止递归
// 划分阶段
val mid = (left + right) / 2 // 计算中点
val mid = left + (right - left) / 2 // 计算中点
mergeSort(nums, left, mid) // 递归左子数组
mergeSort(nums, mid + 1, right) // 递归右子数组
// 合并阶段
@ -53,4 +53,4 @@ fun main() {
val nums = intArrayOf(7, 3, 2, 6, 0, 1, 5, 4)
mergeSort(nums, 0, nums.size - 1)
println("归并排序完成后 nums = ${nums.contentToString()}")
}
}

@ -41,7 +41,7 @@ def merge_sort(nums: list[int], left: int, right: int):
if left >= right:
return # 当子数组长度为 1 时终止递归
# 划分阶段
mid = (left + right) // 2 # 计算中点
mid = (left + right) // 2 # 计算中点
merge_sort(nums, left, mid) # 递归左子数组
merge_sort(nums, mid + 1, right) # 递归右子数组
# 合并阶段

@ -45,7 +45,7 @@ def merge_sort(nums, left, right)
# 当子数组长度为 1 时终止递归
return if left >= right
# 划分阶段
mid = (left + right) / 2 # 计算中点
mid = left + (right - left) / 2 # 计算中点
merge_sort(nums, left, mid) # 递归左子数组
merge_sort(nums, mid + 1, right) # 递归右子数组
# 合并阶段

@ -10,7 +10,7 @@ fn dfs(nums: &[i32], target: i32, i: i32, j: i32) -> i32 {
if i > j {
return -1;
}
let m: i32 = (i + j) / 2;
let m: i32 = i + (j - i) / 2;
if nums[m as usize] < target {
// 递归子问题 f(m+1, j)
return dfs(nums, target, m + 1, j);

@ -48,7 +48,7 @@ fn merge_sort(nums: &mut [i32], left: usize, right: usize) {
}
// 划分阶段
let mid = (left + right) / 2; // 计算中点
let mid = left + (right - left) / 2; // 计算中点
merge_sort(nums, left, mid); // 递归左子数组
merge_sort(nums, mid + 1, right); // 递归右子数组

@ -35,9 +35,7 @@ fn counting_sort_digit(nums: &mut [i32], exp: i32) {
counter[d] -= 1; // 将 d 的数量减 1
}
// 使用结果覆盖原数组 nums
for i in 0..n {
nums[i] = res[i];
}
nums.copy_from_slice(&res);
}
/* 基数排序 */

@ -46,7 +46,7 @@ func mergeSort(nums: inout [Int], left: Int, right: Int) {
return
}
//
let mid = (left + right) / 2 //
let mid = left + (right - left) / 2 //
mergeSort(nums: &nums, left: left, right: mid) //
mergeSort(nums: &nums, left: mid + 1, right: right) //
//

@ -54,7 +54,7 @@ func medianThree(nums: [Int], left: Int, mid: Int, right: Int) -> Int {
/* */
func partitionMedian(nums: inout [Int], left: Int, right: Int) -> Int {
//
let med = medianThree(nums: nums, left: left, mid: (left + right) / 2, right: right)
let med = medianThree(nums: nums, left: left, mid: left + (right - left) / 2, right: right)
//
nums.swapAt(left, med)
return partition(nums: &nums, left: left, right: right)

@ -39,7 +39,7 @@ function mergeSort(nums: number[], left: number, right: number): void {
// 终止条件
if (left >= right) return; // 当子数组长度为 1 时终止递归
// 划分阶段
let mid = Math.floor((left + right) / 2); // 计算中点
let mid = Math.floor(left + (right - left) / 2); // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段

@ -15,10 +15,10 @@ fn merge(nums: []i32, left: usize, mid: usize, right: usize) !void {
const mem_allocator = mem_arena.allocator();
var tmp = try mem_allocator.alloc(i32, right + 1 - left);
std.mem.copy(i32, tmp, nums[left..right+1]);
//
//
var leftStart = left - left;
var leftEnd = mid - left;
//
//
var rightStart = mid + 1 - left;
var rightEnd = right - left;
// i, j
@ -48,7 +48,7 @@ fn mergeSort(nums: []i32, left: usize, right: usize) !void {
//
if (left >= right) return; // 1
//
var mid = (left + right) / 2; //
var mid = left + (right - left) / 2; //
try mergeSort(nums, left, mid); //
try mergeSort(nums, mid + 1, right); //
//
@ -64,4 +64,4 @@ pub fn main() !void {
inc.PrintUtil.printArray(i32, &nums);
_ = try std.io.getStdIn().reader().readByte();
}
}

@ -34,7 +34,7 @@ pub fn BinarySearchTree(comptime T: type) type {
fn buildTree(self: *Self, nums: []T, i: usize, j: usize) !?*inc.TreeNode(T) {
if (i > j) return null;
//
var mid = (i + j) / 2;
var mid = i + (j - i) / 2;
var node = try self.mem_allocator.create(inc.TreeNode(T));
node.init(nums[mid]);
//
@ -145,7 +145,7 @@ pub fn BinarySearchTree(comptime T: type) type {
cur.?.val = tmp_val;
}
}
};
};
}
// Driver Code
@ -179,4 +179,4 @@ pub fn main() !void {
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
_ = try std.io.getStdIn().reader().readByte();
}
}

@ -13,7 +13,7 @@ int dfs(vector<int> &nums, int target, int i, int j) {
return -1;
}
// Calculate midpoint index m
int m = (i + j) / 2;
int m = i + (j - i) / 2;
if (nums[m] < target) {
// Recursive subproblem f(m+1, j)
return dfs(nums, target, m + 1, j);
@ -43,4 +43,4 @@ int main() {
cout << "Index of target element 6 =" << index << endl;
return 0;
}
}

@ -39,7 +39,7 @@ void mergeSort(vector<int> &nums, int left, int right) {
if (left >= right)
return; // Terminate recursion when subarray length is 1
// Partition stage
int mid = (left + right) / 2; // Calculate midpoint
int mid = left + (right - left) / 2; // Calculate midpoint
mergeSort(nums, left, mid); // Recursively process the left subarray
mergeSort(nums, mid + 1, right); // Recursively process the right subarray
// Merge stage

@ -14,7 +14,7 @@ public class binary_search_recur {
return -1;
}
// Calculate midpoint index m
int m = (i + j) / 2;
int m = i + (j - i) / 2;
if (nums[m] < target) {
// Recursive subproblem f(m+1, j)
return dfs(nums, target, m + 1, j);

@ -42,7 +42,7 @@ public class merge_sort {
if (left >= right)
return; // Terminate recursion when subarray length is 1
// Partition stage
int mid = (left + right) / 2; // Calculate midpoint
int mid = left + (right - left) / 2; // Calculate midpoint
mergeSort(nums, left, mid); // Recursively process the left subarray
mergeSort(nums, mid + 1, right); // Recursively process the right subarray
// Merge stage

@ -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

@ -43,7 +43,7 @@ void mergeSort(int *nums, int left, int right) {
if (left >= right)
return; // 當子陣列長度為 1 時終止遞迴
// 劃分階段
int mid = (left + right) / 2; // 計算中點
int mid = left + (right - left) / 2; // 計算中點
mergeSort(nums, left, mid); // 遞迴左子陣列
mergeSort(nums, mid + 1, right); // 遞迴右子陣列
// 合併階段

@ -39,7 +39,7 @@ void mergeSort(vector<int> &nums, int left, int right) {
if (left >= right)
return; // 當子陣列長度為 1 時終止遞迴
// 劃分階段
int mid = (left + right) / 2; // 計算中點
int mid = left + (right - left) / 2; // 計算中點
mergeSort(nums, left, mid); // 遞迴左子陣列
mergeSort(nums, mid + 1, right); // 遞迴右子陣列
// 合併階段

@ -39,7 +39,7 @@ public class merge_sort {
// 終止條件
if (left >= right) return; // 當子陣列長度為 1 時終止遞迴
// 劃分階段
int mid = (left + right) / 2; // 計算中點
int mid = left + (right - left) / 2; // 計算中點
MergeSort(nums, left, mid); // 遞迴左子陣列
MergeSort(nums, mid + 1, right); // 遞迴右子陣列
// 合併階段

@ -36,7 +36,7 @@ void mergeSort(List<int> nums, int left, int right) {
//
if (left >= right) return; // 1
//
int mid = (left + right) ~/ 2; //
int mid = left + (right - left) ~/ 2; //
mergeSort(nums, left, mid); //
mergeSort(nums, mid + 1, right); //
//

@ -46,7 +46,7 @@ func mergeSort(nums []int, left, right int) {
return
}
// 劃分階段
mid := (left + right) / 2
mid := left + (right - left) / 2
mergeSort(nums, left, mid)
mergeSort(nums, mid+1, right)
// 合併階段

@ -42,7 +42,7 @@ public class merge_sort {
if (left >= right)
return; // 當子陣列長度為 1 時終止遞迴
// 劃分階段
int mid = (left + right) / 2; // 計算中點
int mid = left + (right - left) / 2; // 計算中點
mergeSort(nums, left, mid); // 遞迴左子陣列
mergeSort(nums, mid + 1, right); // 遞迴右子陣列
// 合併階段

@ -39,7 +39,7 @@ function mergeSort(nums, left, right) {
// 終止條件
if (left >= right) return; // 當子陣列長度為 1 時終止遞迴
// 劃分階段
let mid = Math.floor((left + right) / 2); // 計算中點
let mid = Math.floor(left + (right - left) / 2); // 計算中點
mergeSort(nums, left, mid); // 遞迴左子陣列
mergeSort(nums, mid + 1, right); // 遞迴右子陣列
// 合併階段

@ -19,7 +19,7 @@ fun merge(nums: IntArray, left: Int, mid: Int, right: Int) {
while (i <= mid && j <= right) {
if (nums[i] <= nums[j])
tmp[k++] = nums[i++]
else
else
tmp[k++] = nums[j++]
}
// 將左子陣列和右子陣列的剩餘元素複製到臨時陣列中
@ -40,7 +40,7 @@ fun mergeSort(nums: IntArray, left: Int, right: Int) {
// 終止條件
if (left >= right) return // 當子陣列長度為 1 時終止遞迴
// 劃分階段
val mid = (left + right) / 2 // 計算中點
val mid = left + (right - left) / 2 // 計算中點
mergeSort(nums, left, mid) // 遞迴左子陣列
mergeSort(nums, mid + 1, right) // 遞迴右子陣列
// 合併階段
@ -53,4 +53,4 @@ fun main() {
val nums = intArrayOf(7, 3, 2, 6, 0, 1, 5, 4)
mergeSort(nums, 0, nums.size - 1)
println("合併排序完成後 nums = ${nums.contentToString()}")
}
}

@ -41,7 +41,7 @@ def merge_sort(nums: list[int], left: int, right: int):
if left >= right:
return # 當子陣列長度為 1 時終止遞迴
# 劃分階段
mid = (left + right) // 2 # 計算中點
mid = left + (right - left) // 2 # 計算中點
merge_sort(nums, left, mid) # 遞迴左子陣列
merge_sort(nums, mid + 1, right) # 遞迴右子陣列
# 合併階段

@ -45,7 +45,7 @@ def merge_sort(nums, left, right)
# 當子陣列長度為 1 時終止遞迴
return if left >= right
# 劃分階段
mid = (left + right) / 2 # 計算中點
mid = left + (right - left) / 2 # 計算中點
merge_sort(nums, left, mid) # 遞迴左子陣列
merge_sort(nums, mid + 1, right) # 遞迴右子陣列
# 合併階段

@ -48,7 +48,7 @@ fn merge_sort(nums: &mut [i32], left: usize, right: usize) {
}
// 劃分階段
let mid = (left + right) / 2; // 計算中點
let mid = left + (right - left) / 2; // 計算中點
merge_sort(nums, left, mid); // 遞迴左子陣列
merge_sort(nums, mid + 1, right); // 遞迴右子陣列

@ -46,7 +46,7 @@ func mergeSort(nums: inout [Int], left: Int, right: Int) {
return
}
//
let mid = (left + right) / 2 //
let mid = left + (right - left) / 2 //
mergeSort(nums: &nums, left: left, right: mid) //
mergeSort(nums: &nums, left: mid + 1, right: right) //
//

@ -54,7 +54,7 @@ func medianThree(nums: [Int], left: Int, mid: Int, right: Int) -> Int {
/* */
func partitionMedian(nums: inout [Int], left: Int, right: Int) -> Int {
//
let med = medianThree(nums: nums, left: left, mid: (left + right) / 2, right: right)
let med = medianThree(nums: nums, left: left, mid: left + (right - left) / 2, right: right)
//
nums.swapAt(left, med)
return partition(nums: &nums, left: left, right: right)

@ -39,7 +39,7 @@ function mergeSort(nums: number[], left: number, right: number): void {
// 終止條件
if (left >= right) return; // 當子陣列長度為 1 時終止遞迴
// 劃分階段
let mid = Math.floor((left + right) / 2); // 計算中點
let mid = Math.floor(left + (right - left) / 2); // 計算中點
mergeSort(nums, left, mid); // 遞迴左子陣列
mergeSort(nums, mid + 1, right); // 遞迴右子陣列
// 合併階段

@ -15,10 +15,10 @@ fn merge(nums: []i32, left: usize, mid: usize, right: usize) !void {
const mem_allocator = mem_arena.allocator();
var tmp = try mem_allocator.alloc(i32, right + 1 - left);
std.mem.copy(i32, tmp, nums[left..right+1]);
//
//
var leftStart = left - left;
var leftEnd = mid - left;
//
//
var rightStart = mid + 1 - left;
var rightEnd = right - left;
// i, j
@ -48,7 +48,7 @@ fn mergeSort(nums: []i32, left: usize, right: usize) !void {
//
if (left >= right) return; // 1
//
var mid = (left + right) / 2; //
var mid = left + (right - left) / 2; //
try mergeSort(nums, left, mid); //
try mergeSort(nums, mid + 1, right); //
//
@ -64,4 +64,4 @@ pub fn main() !void {
inc.PrintUtil.printArray(i32, &nums);
_ = try std.io.getStdIn().reader().readByte();
}
}

@ -34,7 +34,7 @@ pub fn BinarySearchTree(comptime T: type) type {
fn buildTree(self: *Self, nums: []T, i: usize, j: usize) !?*inc.TreeNode(T) {
if (i > j) return null;
//
var mid = (i + j) / 2;
var mid = i + (j - i) / 2;
var node = try self.mem_allocator.create(inc.TreeNode(T));
node.init(nums[mid]);
//
@ -145,7 +145,7 @@ pub fn BinarySearchTree(comptime T: type) type {
cur.?.val = tmp_val;
}
}
};
};
}
// Driver Code
@ -179,4 +179,4 @@ pub fn main() !void {
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
_ = try std.io.getStdIn().reader().readByte();
}
}

Loading…
Cancel
Save