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:
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.