簡體   English   中英

如何有效地將一個數組與另一個數組排序

[英]How to efficiently sort one array by another

假設我有以下設置:

double[] vectorUsedForSorting = new double[] { 5.8,6.2,1.5,5.4 }
double[] vectorToBeSorted = new double[] {1.1,1.2,1.3,1.4}

我想根據vectorToBeSorted的自然數值排序對vectorUsedForSorting排序。

例如,自然順序為[1.5,5.4,5.8,6.2] ,它對應於索引[2,3,0,1] ,這意味着我希望排序函數的輸出為[1.3,1.4,1.1,1.2]

如何以最絕對的效率/最快的方式做到這一點? 我主要關心時間復雜性,因為我將對1,000,000個長度的數組進行此操作。

快速/高效的答案將獎勵大量獎金。

簡單的解決方案:

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));

    }
}

這確實需要一些輔助數組和對象的額外內存,但是執行時間應該接近最佳。

在第一個表上執行歸並排序,並在第二個表上同時執行相同的操作。 保證復雜性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM