c sort keeping track of indices
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
When sorting an array in C++, you sometimes need to know the original positions of elements after sorting. The standard std::sort rearranges elements in-place and discards positional information. To track original indices, you sort an array of indices based on the values they reference, or sort pairs of (value, index).
Method 1: Sort an Index Array
Create a separate index array and sort it using the values as comparison keys:
This is the most common and efficient approach — the original array remains unchanged.
Method 2: Sort Pairs of (Value, Index)
Pack each value with its original index, then sort the pairs:
Method 3: Using a Struct
For complex data where you want to track multiple fields:
Method 4: Using std::stable_sort
If you need to preserve the relative order of equal elements:
Getting the Rank of Each Element
Sometimes you need the inverse mapping — for each element, what is its rank after sorting:
Practical Example: Top-K Elements
Find the indices of the k largest elements:
Common Pitfalls
- Space Complexity: The additional space required is O(n) due to the need to store the indices or pairs.
- Stability:
std::sortis not guaranteed to be stable. Usestd::stable_sortif you need equal elements to preserve their original relative order. - Avoiding Too Much Copying: If the element type is expensive to copy, sort an index array (Method 1) rather than pairs. The index array only moves integers.
- Lambda capture: When sorting indices with a lambda, capture the values array by reference (
[&values]), not by value, to avoid copying the entire array. - Integer overflow: When computing ranks or using indices as offsets, ensure your index type can hold the array size. Use
size_torint64_tfor very large arrays.
Summary
- Sort an index array with a custom comparator referencing the original values (most common)
- Use
std::iotato initialize index arrays:[0, 1, 2, ..., n-1] - Use
std::stable_sortwhen equal elements must preserve their original order - Invert the sorted index array to get per-element ranks
- For top-K problems, use
std::partial_sortfor better performance than full sorting
Related reading
- C STL algorithm equal
- C using standard algorithms with strings, count_if with isdigit, function cast
- Cache Invalidation — Is there a General Solution?
- Cache Oblivious algorithms for parallel programming?
- C standard library - when should I use it and when shouldn't I?
- C stdasync run on main thread
- Cache oblivious lookahead array
- Calculate minimal operations to make two tree structures identical

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.