简体   繁体   中英

Finding original 2d sorted array indexes

I've got this array

Array    Index
[3,5]  - 0
[1,7]  - 1
[12,4] - 2
[3,2]  - 3

And I'm using this sort

Arrays.sort(array, (Integer[] int1, Integer[] int2) -> {
        Integer numberOfKeys1 = int1[1];
        Integer numberOfKeys2 = int2[1];
        return numberOfKeys1.compareTo(numberOfKeys2);
});

To get

Array    Index    Index I want 
[3,2]  - 0      - 3
[12,4] - 1      - 2
[3,5]  - 2      - 0
[1,7]  - 3      - 1

So my question is. How can I get original indexes of sorted 2d array?

Added 3rd row with indexes

array[i][2] = i;

and then ran the sort. Solved, working.

You could define a class containing an array and the original index.

class ArrayIndex {

    Integer[] data;
    int originalIndex;
}

and then sort an ArrayIndex[] array like this :

Arrays.sort(array, (ArrayIndex a, ArrayIndex b) -> 
        Integer.compare(a.data[1], b.data[1])
);

Note above how the Integer.compare method simplifies the comparison and avoids boxing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM