简体   繁体   English

java中如何根据数组的值对数组进行排序

[英]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 }值 = {5, 1, 4 }

The resulting rank array will be: {1, 3 ,2}结果排名数组将是:{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 :(你不能使用排序,所以我没有看到任何方法可以避免O(NxN)渐近复杂度和O(N)辅助空间:(

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;循环遍历数组并初始化 TreeMap rankMap,其中 Rank = {int rank = 0;},通过放入 map key = input[I] 和 value = 默认新 Rank 实例; complexity ≈ O(N*log(N));复杂度≈ O(N*log(N)); memory ≈ O(N)内存≈ O(N)
  2. S = rankMap.size(); S = rankMap.size();
  3. Iterate through the map by initialising Rank instances by S - I: smallest entry is of rank S;通过 S - I 初始化 Rank 实例来遍历映射:最小条目的等级为 S; O(N) operation; O(N) 操作;
  4. loop through original array and output stream of rankMap.get(input[i]).rank values;循环遍历 rankMap.get(input[i]).rank 值的原始数组和输出流;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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