Skip to content

Instantly share code, notes, and snippets.

@Staticity
Created July 21, 2017 19:44
Show Gist options
  • Save Staticity/de566c322ade48c275e3c4f472c43fb7 to your computer and use it in GitHub Desktop.
Save Staticity/de566c322ade48c275e3c4f472c43fb7 to your computer and use it in GitHub Desktop.
Sort elements of an array without modifying the original array
#include <algorithm>
#include <iostream>
int main()
{
// Original data won't change order
const std::vector<int> data{1, 7, 3, 6, 4, 5, 2, 8, 0, 9};
// The objective is to make `data[sortedIndices[i]]` represent
// the following pseudocode: `sorted(data)[i]`.
//
// This means that `sortedIndices` represents the index of each
// element in `data` if `data` were to be sorted.
std::vector<int> sortedIndices(data.size());
// This just fills `sortedIndices` with elements:
// `[0, 1, 2, 3, ..., sortedIndices.size() - 1]`
std::iota(sortedIndices.begin(), sortedIndices.end(), 0);
// Sort the indices based on elements of `data`
std::sort(
sortedIndices.begin(),
sortedIndices.end(),
[&](int i, int j) { return data[i] < data[j]; });
// Now we can print the elements of `data` in order
for (auto sortedIndex : sortedIndices)
{
std::cout << data[sortedIndex] << ' ';
}
std::cout << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment