How to sort an array and keep track of the index in java

后端 未结 3 946
一整个雨季
一整个雨季 2021-01-01 23:29

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[         


        
3条回答
  •  自闭症患者
    2021-01-01 23:43

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

    public class Pair implements Comparable {
        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);
        }
    }
    

    Then, when you're going to sort:

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

    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. 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.

提交回复
热议问题