Created
May 24, 2012 16:06
-
-
Save Prinzhorn/2782445 to your computer and use it in GitHub Desktop.
Sort an array and keep track of all permutations in second array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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