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

pull/897/head
liuyuxin 1 year ago committed by GitHub
parent bd8cda325e
commit 1ab83bd3ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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

Loading…
Cancel
Save