如何在java中对数组进行排序并跟踪索引 [英] How to sort an array and keep track of the index in java

查看:26
本文介绍了如何在java中对数组进行排序并跟踪索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对一个整数数组进行排序(递减),但要跟踪原始索引.

I am trying to sort (decreasing) an array of integers but keeping track of the original index.

我的意思是,例如,如果我有这个数组:

I mean, for example if I have this array:

b[] = { 4, 5, 3, 5, 2 }   

使用 Arrays.sort(b, Collections.reverseOrder()) 后变成(我使用的是 Arrays.sort,因为在这个例子中 b 的长度只有 5,但在我的问题中 b 的长度可能是 1 < b.length < 70

after using Arrays.sort(b, Collections.reverseOrder()) it turns into ( I am using Arrays.sort, because in this example b is only length 5, but in my problem the length of b could be 1 < b.length < 70

b[] = { 5, 5, 4, 3, 2 }

但我想以某种方式拥有原始索引,我的意思是知道

but I want to somehow have the original index, I mean knowing that

bOrignalIndex[] = { 1, 3, 0, 2, 4 }

我不知道我的问题是否清楚,请问我一切.我有一段用 C++ 编写的代码,它会很有帮助,因为它可以满足我的需求

I don't know if my question in clear, please ask me everything. I have this piece of code in C++ that can be helpful because it does what I want

n=4
m=5
tord[] =  
[0] 0   
[1] 1   
[2] 2   
[3] 3   
ts[] =      
[0] 4   
[1] 5   
[2] 3   
[3] 5   



   tord[MAXT], ts[MAXT];
       bool ord(int a, int b){
        return ts[a] > ts[b];    }
    int main(void){
        for(int m, n; scanf("%d %d", &m, &n)){
            bool possible = true;
            FOR(i=0;i<m, i++){ // for each team
                scanf("%d", ts + i); // read team size
                tord[i] = i;
            }
            sort(tord, tord + m, ord)

事情是这样做了之后,tord有按索引排序的数组,即:

The thing is after doing this, tord has the array ordered by index, that is:

tord[] =  
[0] 1   
[1] 3   
[2] 0   
[3] 2   

推荐答案

尝试对按值比较的 (value, index) 对进行排序:

Try sorting pairs of (value, index) compared by value:

public class Pair implements Comparable<Pair> {
    public final int index;
    public final int value;

    public Pair(int index, int value) {
        this.index = index;
        this.value = value;
    }

    @Override
    public int compareTo(Pair other) {
        //multiplied to -1 as the author need descending sort order
        return -1 * Integer.valueOf(this.value).compareTo(other.value);
    }
}

然后,当您要排序时:

public static void main(String[] args) {
    Pair[] yourArray = new Pair[10];

    //fill the array
    yourArray[0] = new Pair(0, 5); yourArray[1] = new Pair(1, 10); //and so on
    Arrays.sort(yourArray);
}

现在,您有一个 Pair 对象数组,按 value 降序排列.每个对象还包含 index - 在原始数组中的位置.

Now, you have an array of Pair object ordered by value descending. Each object also contains index- the place in the original array.

P.S. 我用 Java 编写了示例,因为问题具有 java 标记.虽然在C++中思路是一样的,只是实现上有点不同.

P. S. I wrote the sample in Java as the question has java tag. Although, in C++ the idea is the same, only the implementation is a little bit different.

这篇关于如何在java中对数组进行排序并跟踪索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆