Suppose I have the following setup:
double[] vectorUsedForSorting = new double[] { 5.8,6.2,1.5,5.4 }
double[] vectorToBeSorted = new double[] {1.1,1.2,1.3,1.4}
I would like to sort vectorToBeSorted
based on the natural numerical ordering of vectorUsedForSorting
.
For example, the natural ordering would be [1.5,5.4,5.8,6.2]
which corresponds to indices [2,3,0,1]
, which would mean I want the output of the sorting function to be [1.3,1.4,1.1,1.2]
.
How do I do this in the most absolute efficient/fast possible way? I am mostly concerned with time-complexity since I will be doing this for 1,000,000 length arrays.
A large bonus will be awarded to a fast/efficient answer.
The simple solution:
class D implements Comparable<D> {
double key;
double value;
@Override
public int compareTo(D other) {
return Double.compare(key, other.key);
}
}
public class Test {
public static void main(String[] args) {
double[] vectorUsedForSorting = new double[] { 5.8,6.2,1.5,5.4 };
double[] vectorToBeSorted = new double[] {1.1,1.2,1.3,1.4};
D[] array = new D[vectorUsedForSorting.length];
for (int i = 0; i < array.length; i++) {
array[i] = new D();
array[i].key = vectorUsedForSorting[i];
array[i].value = vectorToBeSorted[i];
}
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
vectorToBeSorted[i] = array[i].value;
}
System.out.println(Arrays.toString(vectorToBeSorted));
}
}
This does require a little extra memory for the auxiliary array and objects, but should come close to optimal in execution time.
Perform merge-sort on the first table, and do the same operations on the second table at the same time. Complexity nlogn guaranteed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.