I seem to have come across what's basically a leetcode question in some actual practical code I'm writing. My problem is that I need to sort an array using a reference array of indices and a swap function.
It may help to know the context of this problem. It's a simplified, isolated version of what I'm facing when trying to come up with a script to sort layers by object position within Adobe Illustrator via ExtendScript. That's why swapping is necessary, and that's why there's a reference array as opposed to just using the .sort() function.
The arrayToBeSorted contains the actual data that I'm trying to sort. The referenceArray is an already-sorted list of the indices of arrayToBeSorted. This referenceArray describes what order the items in the arrayToBeSorted should end up in, by referring the indices of the items in arrayToBeSorted.
Setup Example 1:
// index 0 1 2 3 4 5
arrayToBeSorted = [ "six", "four", "one", "three", "two", "five" ]
referenceArray = [ 2, 4, 3, 1, 5, 0 ]
function swapItems(a, b) {
var temp = arrayToBeSorted[a];
arrayToBeSorted[a] = arrayToBeSorted[b];
arrayToBeSorted[b] = temp;
}
// desired outcome:
algorithmToSortArray(arrayToBeSorted, referenceArray)
// should return this:
[
"one", // was arrayToBeSorted[2]
"two", // was arrayToBeSorted[4]
"three", // was arrayToBeSorted[3]
"four", // was arrayToBeSorted[1]
"five", // was arrayToBeSorted[5]
"six" // was arrayToBeSorted[0]
]
Setup Example 2:
// index 0 1 2 3 4 5
arrayToBeSorted = [ "red", "green", "blue", "pink", "purple", "orange" ]
referenceArray = [ 5, 1, 4, 2, 0, 3 ]
function swapItems(a, b) {
var temp = arrayToBeSorted[a];
arrayToBeSorted[a] = arrayToBeSorted[b];
arrayToBeSorted[b] = temp;
}
// desired outcome:
algorithmToSortArray(arrayToBeSorted, referenceArray)
// should return this:
[
"orange", // was arrayToBeSorted[5]
"green", // was arrayToBeSorted[1]
"purple", // was arrayToBeSorted[4]
"blue", // was arrayToBeSorted[2]
"red", // was arrayToBeSorted[0]
"pink" // was arrayToBeSorted[3]
]
Solution constraints:
The solution should exclusively use the swap function to move items around in arrayToBeSorted in-place, and should preferably be optimized for the least number of swaps possible.
What would be the best way to write algorithmToSortArray()?
.sort()?.sort()because this problem is an abstraction for sorting layers via scripting within an Adobe program, where .sort() wouldn't work.const result = referenceArray .map (i => arrayToBeSorted [i])? This does not swap in place, but maps; however it is quite simpler.