gpt4 book ai didi

javascript - 使用 JavaScript 中的快速排序根据另一个数组对一个数组进行排序

转载 作者:行者123 更新时间:2023-11-28 17:35:34 25 4
gpt4 key购买 nike

我想根据c的升序对a进行排序。 c 通过此方法进行排序,但 a 没有,a 在代码末尾只有四个未排序的元素。我应该做出哪些改变?

var a = ['e','b','d','a','f','g','c'];
function quick_Sort(origArray,a) {
var i;
var length = origArray.length;
if (origArray.length <= 1) {
return [origArray, a];
} else {

var left = [];
var right = [];
var left1 = [];
var right1 = [];
var newArray = [];
var newArray1 = [];
var pivot = origArray.pop();
var pivot1 = a.pop();

for (i = 0; i < length-1; i++) {
if (origArray[i] <= pivot) {
left.push(origArray[i]);
left1.push(a[i]);
} else {
right.push(origArray[i]);
right1.push(a[i]);
}
}
return [newArray.concat((quick_Sort(left, left1)[0]), pivot, (quick_Sort(right, right1)[0])),newArray1.concat((quick_Sort(left, left1)[1]), pivot1, (quick_Sort(right, right1)[1]))];
}
}

var c = [3, 0, 2, 5, -1, 4, 1 ];

console.log("Original array: " + c);
console.log("Original array: " + a);
var e = quick_Sort(c,a);
c = e[0];
a = e[1];
console.log("Sorted array: " + c);
console.log("Sorted array: " + a);

最佳答案

如果您想根据 c 的相应值对 a 进行排序,您可以:

var a = ['e','b','d','a','f','g','c'];
var c = [3, 0, 2, 5, -1, 4, 1 ];

var [sortedA, sortedC] = a.map((v,i) => [ v, c[i] ] ) //Pair the a and c
.sort((x,y)=>x[1] - y[1]) //Sort the array based on the c value
.reduce((c,v) => {
c[0].push( v[0] );
c[1].push( v[1] );
return c;
}, [[],[]]); //Seperate the a and c

console.log( sortedA );
console.log( sortedC );

关于javascript - 使用 JavaScript 中的快速排序根据另一个数组对一个数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com