Keep track of previous indexes after sorting a vector in C++ STL
Prerequisite: vector, vector pair sorting Given a vector, keep track of the present indexes corresponding to each element and after sorting print element with its previous respective indexes. Examples:
Input: Arr[] = {2, 5, 3, 7, 1} Output: {1, 4} {2, 0} {3, 2} {5, 1} {7, 3} Explanation: Before sorting [index(element)]: [0(2), 1(5), 2(3), 3(7), 4(1)] After sorting [previous_index(element)]: [4(1), 0(2), 2(3), 1(5), 3(7)] Input: Arr[] = {4, 5, 10, 8, 3, 11} Output: {3, 4} {4, 0} {5, 1} {8, 3} {10, 2} {11, 5}
Approach: The idea is to store each element with its present index in a vector pair and then sort all the elements of the vector, Finally, print the elements with its index associated with it. Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void sortArr( int arr[], int n)
{
vector<pair< int , int > > vp;
for ( int i = 0; i < n; ++i) {
vp.push_back(make_pair(arr[i], i));
}
sort(vp.begin(), vp.end());
cout << "Element\t"
<< "index" << endl;
for ( int i = 0; i < vp.size(); i++) {
cout << vp[i].first << "\t"
<< vp[i].second << endl;
}
}
int main()
{
int arr[] = { 2, 5, 3, 7, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
sortArr(arr, n);
return 0;
}
|
Output:
Element index
1 4
2 0
3 2
5 1
7 3
Time Complexity: O(n*logn) where n is size of input array. This is because sort stl function has been called which takes O(n*logn) time. Also there is O(n) time contributed by for loop running in sortArr fucniton but sort has dominating factor. So, overall time complexity is O(n*logn).
Space Complexity: O(n) where n is size of the input array. This is because a vector vp has been created.
Last Updated :
13 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...