Reputation: 133
I want to sort a
, according to ascending order of c
. c
gets sorted by this method, but a
doesn't, a
has only four unsorted elements at the end of code. What changes should I make?
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);
Upvotes: 0
Views: 58
Reputation: 26844
If you want to sort a
from the corresponding value of c
you can:
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 );
Upvotes: 3