I'm working on an algorithm that works best if the inputs are passed to it in a particular order, so I want to sort them that way. The difference is drastic enough for me to consider re-sorting the array.
Consider an array a
with length n
. I want to sort it the following way, and return the array of indices of a
instead of the values:
I define another array w
, also of length n
. I want to sort such that the first element is closest to the first element of w
. Then, from the rest of the elements (excluding the one already sorted), the second element is closest to the second element of w
, and so on.
For example a = {5.5, 6.5, 2.4, 3.1}
, w = {1, 2, 6, 5}
.
2.4
is closest to 1
, so output[0] = 2
, the index of 2.4
.
2.4
is closest to 2
, but already processed, so choose 3.1
, output[1] = 3
.
Next come 0
and 1
, in that order. 0
is chosen because it comes first, although both are equidistant.
So, output = {2, 3, 0, 1}
and the sorted array would be sorted = {2.4, 3.1, 5.5, 6.5}
(each index is used to find the corresponding element).
I can only think of brute-forcing this algorithm. Can there be a more efficient way to do it?
Sort()
functions that I'm aware of let you provide your ownCompare(a,b)
function. That would let you sort (for example) a list of strings by length instead of alphabet.a
andw
might look like before and after processing?