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

后端 未结 3 949
一整个雨季
一整个雨季 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-02 00:08

    The OP poster's example involved sorting an array of integer. If any of the readers have a similar situation, but with an array of non-primitive types, the following is a class that handles this for arrays of non-primitives. The class takes a somewhat different approach. It leaves the original array unmodified but instead creates an array of indexes and sorts and returns that.

    public class IndirectSorter> {
        public int[] sort(T args[]) {
            Integer origindex[] = new Integer[args.length];
            int retval[] = new int[args.length];
            for (int i=0; i(args));
            for (int i=0; i> implements Comparator {
            T args[];
            public IndirectCompareClass(T args[]) { this.args = args; }
            public int compare( Integer in1, Integer in2 ) {
                return args[in1.intValue()].compareTo(args[in2.intValue()]);
            }
            public boolean equals( Integer in1, Integer in2 ) {
                return args[in1.intValue()].equals(args[in2.intValue()]);
            }
        }
    }
    

    And to call it quickly you can do something like this:

    public static void main(String args[] ) {
        int indexes[] = new IndirectSorter().sort(args);
        for (int i : indexes) {
            System.out.printf("original pos: %d %s\n", i, args[i] );
        }
    }
    

    Edit: If you're willing to reimplement the Arrays.sort(int[]) method, you can avoid the creation and use of Integer objects. This can be appealing.

提交回复
热议问题