Open In App

Keep track of previous indexes after sorting a vector in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ implementation to keep track
// of previous indexes
// after sorting a vector
 
#include <bits/stdc++.h>
using namespace std;
 
void sortArr(int arr[], int n)
{
 
    // Vector to store element
    // with respective present index
    vector<pair<int, int> > vp;
 
    // Inserting element in pair vector
    // to keep track of previous indexes
    for (int i = 0; i < n; ++i) {
        vp.push_back(make_pair(arr[i], i));
    }
 
    // Sorting pair vector
    sort(vp.begin(), vp.end());
 
    // Displaying sorted element
    // with previous indexes
    // corresponding to each element
    cout << "Element\t"
         << "index" << endl;
    for (int i = 0; i < vp.size(); i++) {
        cout << vp[i].first << "\t"
             << vp[i].second << endl;
    }
}
 
// Driver code
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
Previous
Next
Share your thoughts in the comments
Similar Reads