Java-根据另一个数组对数组进行排序

时间:2018-12-03 10:47:41

标签: java sorting

我有一种方法,该方法基于JSON创建两个数组:int类型的数组的索引

int[] indices;

和类型为double的相关性数组

double[] relevance;

保证两个数组在设置后具有相同的大小。 我需要根据相关性数组中的值来检索索引的排序数组。示例:

indices = {5, 8, 3, 2}
relevance = {0.1234, 0.3567, 0.2254, 0.0005}

返回的结果将是:

{2, 5, 3, 8}

我目前的解决方案是使用自定义排序功能(气泡排序),该功能可以比较相关性数组的值并交换相关性和索引数组中的值。

有没有更时尚的方法来解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以创建同时包含相关性和索引的对象,然后将该对象放入新的列表中。现在,您可以按相关性对该列表进行排序,并获取相应的索引。

类似的东西:

// Class holding relevance and index at the same time
public class RelevanceIndex {
  private int index;
  private double relevance;
  ...
}

// Create and populate a list of RelevanceIndex
List<RelevanceIndex> relevanceIndexes = new ArrayList<>();
for (int i = 0; i < indices.length; i++) {
  RelevanceIndex relevanceIndex = new RelevanceIndex();
  relevanceIndex.setIndex(indexes[i]);
  relevanceIndex.setRelevance(relevances[i]);
  relevanceIndexes.add(relevanceIndex);
}

...
// Sort relevanceIndexes by relevance using method sort of List
// (you need to define your Comparator or define RelevanceIndex as
// Comparable)
// Now you have the related indexes sorted. If necessary you can put them 
// in a new sorted array

编辑:添加了此答案的完整实现

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArraySorting {

    public static void main(String[] args) {

        int[] indices = {5, 8, 3, 2};
        double[] relevance = {0.1234, 0.3567, 0.2254, 0.0005};

        ArraySorting app = new ArraySorting();
        app.run(indices, relevance);
    }

    void run(int[] indices, double[] relevance) {
        List<RelevanceIndex> relevanceIndices = getRelevanceIndices(indices, relevance);

        System.out.println(relevanceIndices);
        Collections.sort(relevanceIndices);
        System.out.println(relevanceIndices);
    }

    List<RelevanceIndex> getRelevanceIndices(int[] indices, double[] relevance) {
        List<RelevanceIndex> relevanceIndices = new ArrayList<>();
        for (int i = 0; i < indices.length; i++) {
            relevanceIndices.add(new RelevanceIndex(indices[i], relevance[i]));
        }
        return relevanceIndices;
    }

    class RelevanceIndex implements Comparable<RelevanceIndex> {
        private int index;
        private double relevance;

        RelevanceIndex(int index, double relevance) {
            this.index = index;
            this.relevance = relevance;
        }

        @Override
        public int compareTo(RelevanceIndex other) {
            return Double.compare(this.relevance, other.relevance);
        }

        @Override
        public String toString() {
            return String.format("%s (%s)", index, relevance);
        }
    }
}