使用C++编写的数组元素排序的排名

2023年 8月 27日 15.2k 0

使用C++编写的数组元素排序的排名

在给定的问题中,我们需要对数组的所有给定元素进行排名,最小的数字具有最小的排名,最大的具有最大的排名。例如,我们还需要根据数字的频率来更改数字的排名 -

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

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论