Convert an array to reduced form (Using vector of pairs) in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to convert an array to its reduced form using vector of pairs.

For this we will be provided with an array. Our task is to convert the given array in its reduced form such that it only contains elements ranging from 0 to n-1.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//converting array to its reduced form
void convert(int arr[], int n){
   //creating a vector of pairs
   vector <pair<int, int> > v;
   //putting elements in vector
   //with their indexes
   for (int i = 0; i < n; i++)
      v.push_back(make_pair(arr[i], i));
   sort(v.begin(), v.end());
   for (int i=0; i<n; i++)
   arr[v[i].second] = i;
}
//printing the array
void print_array(int arr[], int n) {
   for (int i=0; i<n; i++)
      cout << arr[i] << " ";
}
int main(){
   int arr[] = {10, 20, 15, 12, 11, 50};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Given Array is :\n";
   print_array(arr, n);
   convert(arr , n);
   cout << "\nConverted Array:\n";
   print_array(arr, n);
   return 0;
}

Output

Given Array :
10 20 15 12 11 50
Converted Array:
0 4 3 2 1 5
raja
Published on 16-Jan-2020 11:30:26
Advertisements