0

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.

2
  • A) write sort B) pass both arrays C) sort both simultaneously only based on values from first. Commented Feb 7, 2014 at 21:58
  • Have you changed your mind w.r.t. the previous question? Now you really need sorting? Commented Feb 7, 2014 at 22:42

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This algorithm is O(nlogn) since Arrays.sort() is O(nlogn). This is probably as good as it gets.
This gives 560 milliseconds for 1 million datapoints. Good enough.
2

Perform merge-sort on the first table, and do the same operations on the second table at the same time. Complexity nlogn guaranteed

2 Comments

Hmm I'm not sure, can you write a method? I will award bonus.
Yeah it's fine. I will write something and if it's faster than meriton I will aware you the answer. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.