简体   繁体   English

如何有效地将一个数组与另一个数组排序

[英]How to efficiently sort one array by another

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 . 我想根据vectorToBeSorted的自然数值排序对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] . 例如,自然顺序为[1.5,5.4,5.8,6.2] ,它对应于索引[2,3,0,1] ,这意味着我希望排序函数的输出为[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. 我主要关心时间复杂性,因为我将对1,000,000个长度的数组进行此操作。

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 保证复杂性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM