简体   繁体   中英

How to rank an array according to values of the array in java

I have to rank the array according to the values, in the same position. For Example:

Values = {5, 1, 4 }

The resulting rank array will be: {1, 3 ,2}

How can I achieve this without sorting the array?

You should write something like this:

public static int[] getRanksArray(int[] array) {
    int[] result = new int[array.length];

    for (int i = 0; i < array.length; i++) {
        int count = 0;
        for (int j = 0; j < array.length; j++) {
            if (array[j] > array[i]) {
                count++;
            }
        }
        result[i] = count + 1;
    }
    return result;
}

this method returns array with ranks which index corresponds to value index in input array (if the values are equal they share one common rank)

You cannot use sorting, so I don't see any way to avoid O(NxN) asymptotic complexity and O(N) auxiliary space :(

If you cannot use explicit sort, use implicit one:

  1. loop through array and initialise TreeMap rankMap, where Rank = {int rank = 0;}, by putting into map key = input[I] and value = default new Rank instance; complexity ≈ O(N*log(N)); memory ≈ O(N)
  2. S = rankMap.size();
  3. Iterate through the map by initialising Rank instances by S - I: smallest entry is of rank S; O(N) operation;
  4. loop through original array and output stream of rankMap.get(input[i]).rank values;

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