Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Replace each element by its rank given in array using C++

Replace each element by its rank given in array in C++

In this article, we will brief in on how to replace each element by its rank in the given array. There is an array of n elements, replace each element of the array by its corresponding rank.The minimum value element will have the highest rank.

Replace each element of the array by its rank

Algorithm

  • Use Map to replace each element by it’s rank.
  • The array element and its index are stored in two columns in the map
  • Store the element in sorted order .
  • Start iterating it, the elements will be in an increasing order sequence.
  • Assign values for each element in increasing order
  • Starting from 1 to k incrementing by 1 for each element.
  • Later the index is replaced by the element’s rank

C++ Code Based on above algorithm

#include <bits/stdc++.h>

using namespace std;

void change (int array[], int k)
{
map < int, int >map;
for (int x = 0; x < k; x++)
map[array[x]] = x;
int rank = 1;

for (auto x:map)
array[x.second] = rank++;
}

int main ()
{
int k;
cout << "Enter the size :";
cin >> k;
int array[k];
cout << "Array elements : ";
for (int x = 0; x < k; x++)
cin >> array[x];
change (array, k);

cout << "Elements afer replacement : ";
for (int x = 0; x < k; x++)
cout << array[x] << " ";

return 0;
}
Input:

Enter the size: 6

Array elements: 9 8 7 6 5 4

Output:

Elements after relacement: 6 5 4 3 2 1