我试图理解所有排序算法,这是我为合并排序编写的代码,但它不起作用,你能指出其中的错误吗:
solve: function (A) {
let count = this.mergeSort(A);
return count;
},
mergeTwoSortedArrays: function (A, B) {
let i = 0;
let j = 0;
let k = 0;
let C = [];
while (i < A.length && j < B.length && A[i] || B[j]) {
if (A[i] < B[j]) {
C[k] = A[i];
i++;
k++;
} else {
C[k] = B[j];
j++;
k++;
}
}
while (j < B.length) {
C[k] = B[j];
k++;
j++;
}
while (i < A.length) {
C[k] = A[i];
k++;
i++;
}
return C;
},
mergeSort: function (a) {
let n = a.length;
if (n <= 1) return a;
let c = Array.from({ length: Math.floor(n / 2) }, (_, i) => a[i]);
let d = Array.from({ length: n - c.length }, (_, i) => a[c.length + i]);
return this.mergeTwoSortedArrays(c, d);
}
问题是要求我添加更多详细信息以使我的帖子获得批准。 所以我的方法是:将数组分成两个相等的部分,直到它们成为 1 个元素的数组,然后使用合并技术合并两个排序后的数组。
你应该简单地检查我< A.length && j < B.length as the loop condition.
这是您的更新代码:
const mergeSort = {
solve: function (A) {
return this.mergeSortFunction(A);
},
mergeTwoSortedArrays: function (A, B) {
let i = 0;
let j = 0;
let k = 0;
let C = [];
while (i < A.length && j < B.length) {
if (A[i] < B[j]) {
C[k] = A[i];
i++;
k++;
} else {
C[k] = B[j];
j++;
k++;
}
}
while (j < B.length) {
C[k] = B[j];
k++;
j++;
}
while (i < A.length) {
C[k] = A[i];
k++;
i++;
}
return C;
},
mergeSortFunction: function (a) {
let n = a.length;
if (n <= 1) return a;
let c = Array.from({ length: Math.floor(n / 2) }, (_, i) => a[i]);
let d = Array.from({ length: n - c.length }, (_, i) => a[c.length + i]);
return this.mergeTwoSortedArrays(this.mergeSortFunction(c), this.mergeSortFunction(d));
}
};
// Example
const inputArray = [38, 27, 43, 3, 9, 82, 10];
const sortedArray = mergeSort.solve(inputArray);
console.log(sortedArray);
// Output: [3, 9, 10, 27, 38, 43, 82]