Find Surpasser Count of each element in array in C++

C++Server Side ProgrammingProgramming

Suppose one array A is given. We have to find a number of surpasser of each element in that array. The surpassers are greater elements which are present at the right side of the array of the current element. Suppose A = {2, 7, 5, 3, 0, 8, 1}, the surpassers are {4, 1, 1, 1, 2, 0, 0}, so 2 has 4 numbers at right side, which are greater than 4, and the same rule for others. The solution is very simple, two nested loops will be there, for each element, it will count surpassers, then store them into another array.

Example

 Live Demo

#include <iostream>
using namespace std;
void gerSurpassers(int arr[], int surpassers[], int n){
   for(int i = 0; i<n; i++){
      int count = 0;
      for(int j = i+1; j<n; j++){
         if(arr[j] > arr[i])
            count++;
      }
      surpassers[i] = count;
   }
}
void displayArray(int arr[], int n){
   for(int i = 0; i<n; i++){
      cout << arr[i] << " ";
   }
   cout << "\n";
}
int main() {
   int arr[] = {2, 7, 5, 3, 0, 8, 1};
   int n = sizeof(arr) / sizeof(arr[0]);
   int surpassers[n];
   cout << "Elements :"; displayArray(arr, n);
   gerSurpassers(arr, surpassers, n);
   cout << "Surpassers:"; displayArray(surpassers, n);
}

Output

Elements :2 7 5 3 0 8 1
Surpassers:4 1 1 1 2 0 0
raja
Published on 21-Oct-2019 08:05:56
Advertisements