在给定的问题中,我们需要对数组的所有给定元素进行排名,最小的数字具有最小的排名,最大的具有最大的排名。例如,我们还需要根据数字的频率来更改数字的排名 -
Input : 20 30 10
Output : 2.0 3.0 1.0
Input : 10 12 15 12 10 25 12
Output : 1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0
Here the rank of 10 is 1.5 because there are two 10s present in the given array now if we assume they both take different ranks i.e. 1 and 2 and we thus divide it within themselves so their rank becomes 1.5 and 1.5.
Input : 1, 2, 5, 2, 1, 60, 3
Output : 1.5, 3.5, 6.0, 3.5, 1.5, 7.0, 5.0
登录后复制
寻找解决方案的方法
有两种不同的方法来寻找解决方案,它们是 -
暴力方法
在这种方法中,我们将循环,选择任何特定元素,并确定其排名。
示例
#include
using namespace std;
int main() {
int arr[] = {1, 2, 5, 2, 1, 25, 2}; // given array
int n = sizeof(arr) / sizeof(arr[0]); // size of our given array
float rank[n] = {0}; // our ranking array
for (int i = 0; i < n; i++) {
int r = 1; // the number of elements greater than arr[i]
int s = 1; // the number of elements equal to arr[i]
for (int j = 0; j < n; j++) {
if (j != i && arr[j] < arr[i])
r += 1;
if (j != i && arr[j] == arr[i])
s += 1;
}
rank[i] = r + (float)(s - 1) / (float) 2; // using formula
//to obtain rank of particular element
}
for (int i = 0; i < n; i++) // outputting the ranks
cout