gpt4 book ai didi

Java - 基于另一个数组对数组进行排序

转载 作者:行者123 更新时间:2023-12-02 10:31:23 30 4
gpt4 key购买 nike

我有一个方法,基于一些 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}

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

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

最佳答案

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

类似的事情:

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

关于Java - 基于另一个数组对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53592178/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com