How to find the permutation of a sort in Java

后端 未结 5 1134
攒了一身酷
攒了一身酷 2021-01-11 22:41

I want to sort an array and find the index of each element in the sorted order. So for instance if I run this on the array:

[3,2,4]

I\'d ge

5条回答
  •  旧巷少年郎
    2021-01-11 23:33

    Let's assume your elements are stored in an array.

    final int[] arr = // elements you want
    List indices = new ArrayList(arr.length);
    for (int i = 0; i < arr.length; i++) {
      indices.add(i);
    }
    Comparator comparator = new Comparator() {
      public int compare(Integer i, Integer j) {
        return Integer.compare(arr[i], arr[j]);
      }
    }
    Collections.sort(indices, comparator);
    

    Now indices contains the indices of the array, in their sorted order. You can convert that back to an int[] with a straightforward enough for loop.

提交回复
热议问题