Store the data and index of the array element as a pair and sort the array of pairs. Now print only part of the index.
// Original array int arr[] = {3, 2, 6, 4}; // Size of original array const int sz = static_cast<int>(sizeof arr / sizeof arr[0]); // Array of pair {.first = item, .second = 1-based index std::vector< pair<int, int> > vp(sz); // std::array if size is fixed for(int i = 0; i < sz; ++i) vp[i] = make_pair(arr[i], i + 1); /* Can be done in a more fancy way using std::transform + lambda */ // Sort the array, original array remains unchanged std::sort(vp.begin(), vp.end()); // Print the result for(int i = 0; i < sz; ++i) cout << ' ' << vp[i].second;
Living code
Temporary code complexity: O (N log N) , where N is the number of elements in the array
From the comment, since the value of N is large and all numbers are different, you can use the following snippet
int maxn = maximum value of a number; int positions[maxn] = {0}; // Or choose a sparse array with constant update time int arr[] = {3, 2, 6, 4}; const int sz = static_cast<int>(sizeof arr / sizeof arr[0]); for(int i = 0; i < sz; ++i) { assert( arr[i] >= 0 ); position[ arr[i] ] = i + 1; } for(int i = 0; i < maxn; ++i) { if(position[i]) cout << ' ' << position[i]; }
Living code
Temporary code complexity: O (N) , where N is the maximum number
source share