refactor(dart): Re-implement merge sort function (#896)

This commit is contained in:
liuyuxin 2023-10-27 16:00:26 +08:00 committed by GitHub
parent bd8cda325e
commit 1ab83bd3ef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -5,28 +5,29 @@
*/
/* 合并左子数组和右子数组 */
// [left, mid]
// [mid + 1, right]
void merge(List<int> nums, int left, int mid, int right) {
//
List<int> tmp = nums.sublist(left, right + 1);
//
int leftStart = left - left, leftEnd = mid - left;
//
int rightStart = mid + 1 - left, rightEnd = right - left;
// i, j
int i = leftStart, j = rightStart;
// nums
for (int k = left; k <= right; k++) {
// j++
if (i > leftEnd)
nums[k] = tmp[j++];
// <= i++
else if (j > rightEnd || tmp[i] <= tmp[j])
nums[k] = tmp[i++];
// > j++
// [left, mid], [mid+1, right]
// tmp
List<int> tmp = List.filled(right - left + 1, 0);
//
int i = left, j = mid + 1, k = 0;
//
while (i <= mid && j <= right) {
if (nums[i] <= nums[j])
tmp[k++] = nums[i++];
else
nums[k] = tmp[j++];
tmp[k++] = nums[j++];
}
//
while (i <= mid) {
tmp[k++] = nums[i++];
}
while (j <= right) {
tmp[k++] = nums[j++];
}
// tmp nums
for (k = 0; k < tmp.length; k++) {
nums[left + k] = tmp[k];
}
}