Skip to content

Instantly share code, notes, and snippets.

@Prinzhorn
Created May 24, 2012 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prinzhorn/2782445 to your computer and use it in GitHub Desktop.
Save Prinzhorn/2782445 to your computer and use it in GitHub Desktop.
Sort an array and keep track of all permutations in second array
//Sorts arr and syncs assArr simultaneously
var associatedSort = (function() {
var comparator = function(a, b) {
if(a[0] < b[0]) {
return -1;
}
if(a[0] > b[0]) {
return 1;
}
return 0;
};
return function(arr, assArr) {
if(arr.length !== assArr.length) {
throw 'Arrays have different length';
}
//Replace all elements of the array with a helper object containing the element and the corresponding element of the other array.
for(var i = 0; i < arr.length; i++) {
arr[i] = [arr[i], assArr[i]];
}
//Sort
arr.sort(comparator);
//Now assign the old elements and remove the helper object
for(var i = 0; i < arr.length; i++) {
assArr[i] = arr[i][1];
arr[i] = arr[i][0];
}
};
})();
//
//Example
//
var arr1 = [5,7,3,8];
var arr2 = [1,1,2,1];
console.log(arr1);
console.log(arr2);
associatedSort(arr1, arr2);
console.log('sorted:');
console.log(arr1);
console.log(arr2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment