首页 > 文章列表 > 使用C++编写的数组元素排序的排名

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

数组排序 排名 C编程
131 2023-08-29

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

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 <bits/stdc++.h>
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 << rank[i] << ' ';

   return 0;
}

输出

1.5 4 6 4 1.5 7 4

该程序的时间复杂度为O(N*N),其中N是现在给定数组的大小;正如你所看到的,我们的时间复杂度不好,因此我们将提高其效率,以更好地适应更高的约束。

高效方法

在这种方法中,我们将采取一个新数组并对其进行排序,因为数组已排序,现在我们知道相同排名的所有元素将在一起,因此现在我们像往常一样对它们进行排名,然后计算特定元素的排名。

示例

#include <bits/stdc++.h>

using namespace std;

int main() {
   int arr[] = {1, 2, 5, 2, 1, 60, 3}; // given array
   int n = sizeof(arr) / sizeof(arr[0]); // size of our given array
   float rank[n] = {0}; // our ranking array
   int old[n];
   for(int i = 0; i < n; i++)
   old[i] = arr[i];
   sort(arr, arr+n); // sorting the array
   int prev = arr[0];
   int r = 1; // ranks
   int s = 0; // frequency
   int tot = 0; // will stack up all the rank contained by an element
   map<int, float> rrank;

   for (int i = 0; i < n; i++) {
      if(prev == arr[i]) {
         s++;
         tot += r;
      } else {
         float now = 0;
         now = (float)tot/s; // dividing the ranks equally
         rrank[prev] = now;
         prev = arr[i];
         tot = r;
         s = 1;
      }
      r++;
   }
   rrank[arr[n-1]] = (float)tot/s;
   for (int i = 0; i < n; i++) // outputting the ranks
      cout << rrank[old[i]] << " ";

   return 0;
}

输出

1.5 3.5 6 3.5 1.5 7 5

上述代码的说明

在这种方法中,我们对数组进行排序,然后从头开始对每个元素进行排名(排名从 1 开始)。现在,如果我们的上一个元素等于当前元素,我们就会增加 s 并叠加到我们的排名总和。当我们的元素发生更改时,我们将前面的元素的排名分开,刷新 s 和总计,然后继续我们的代码。

结论

在本文中,我们解决了一个问题来找到数组中所有元素的排名。我们还学习了解决这个问题的C++程序以及解决这个问题的完整方法(正常且高效)。我们可以用其他语言编写相同的程序,例如C、java、python等语言。