简体   繁体   中英

Copying array's indexes as values to new array, sorted by highest values. JAVA

I got an int array[8] with random not repeated values from 0 to 9. It's not sorted. I would like to store indexes of the array in another array starting with highest values.

eg Input array - {9,8,7,3,6,5,2,4}

output array - {0,1,2,4,5,7,3,6}

The 0 index of new array starts with value equals to index with highest value from the first array (descending).

I'm new here, it's my first post and I'm still learning so be forgiving please.

I don't want to sort the first array. ( Don't ask me why :O )

Thanks

Info TreeMap constructor and TreeMap values , and see also Comparator

// treemap is sorted by the keys. Supplementary, you can use your own
// comparator for a custom order
TreeMap<Integer, Integer> valuesToIndexes=
   new TreeMap<>(new Comparator<Integer>() {
     public int compare(Integer a, Integer b) {
       return b-a; // in the inverse order
     }
   })
;
for(int i=0; i<arr.length; i++) {
  valuesToIndexes.put(arr[i], i);
}
// iterating the values of a map will be done in the order of the map's keys
// Since the key is the array value in reverse (and the value is the index)
// we'll be outputting the array indexes in the decreasing order of its values
for(Integer v : valuesToIndexes.values()) {
  System.out.println(v);
}
    //input array
    Integer array[] = {9, 8, 7, 4, 5, 6, 1, 2};
    // originalOrder
    List<Integer> originalOrder = new ArrayList<>(Arrays.asList(array));
    //array to sort
    List<Integer> arrayAsList = Arrays.asList(array);

    Collections.sort(arrayAsList, new Comparator<Integer>() {
        @Override
        public int compare(Integer t, Integer t1) {
            return t1.compareTo(t);
        }
    });

    Integer outputArray[] = new Integer[array.length];

    for (int i = 0; i < arrayAsList.size(); i++) {
        Integer integer = arrayAsList.get(i);
        int index = originalOrder.indexOf(integer);
        outputArray[i] = index;

    }

    // test
    for (Integer integer : outputArray) {
        System.out.println(integer);
    }

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