Javascript JS合并排序,按选择的对象值排序
让我们开始吧,这是我的代码:Javascript JS合并排序,按选择的对象值排序,javascript,algorithm,mergesort,Javascript,Algorithm,Mergesort,让我们开始吧,这是我的代码: function mergeSort(unsortedArray, sortingParameter) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const r
function mergeSort(unsortedArray, sortingParameter) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
// Using recursion to combine the left and right
return merge(mergeSort(left), mergeSort(right), sortingParameter);
}
function merge(left, right, sortingParameter) {
let resultArray = [],
leftIndex = 0,
rightIndex = 0;
if (sortingParameter) {
console.log(left[2][sortingParameter], "parameterCheck");
while (leftIndex < left.length && rightIndex < right.length) {
console.log("while");
if (
left[leftIndex][sortingParameter] < right[rightIndex][sortingParameter]
) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
} else {
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
export { mergeSort };
通过存储在likeCount键上的整数值。。。例如,当我放入一个没有排序参数的整数数组时,这个函数工作得很好
[9,5,7,3,1] => [1,3,5,7,9]
这对我来说是一个很大的头痛,谢谢你提前的帮助 您忘记在mergeSort的递归调用中传递sortingParameter,请参见snippet
函数mergeSort(unsortedArray,sortingParameter){
if(unsortedArray.length)关于如何向函数传递参数,您有没有示例?mergeSort(注释,“likeCount”)
[9,5,7,3,1] => [1,3,5,7,9]