Home > Backend Development > C++ > How Can I Preserve Original Indexes When Sorting Data in C ?

How Can I Preserve Original Indexes When Sorting Data in C ?

Patricia Arquette
Release: 2024-12-30 18:37:09
Original
422 people have browsed it

How Can I Preserve Original Indexes When Sorting Data in C  ?

Preserving Original Indexes During C Sorting

Sorting data while retaining the original indexes is a common requirement in data manipulation tasks. In C , using the standard library, this task encompasses the following steps:

  1. Vector Initialization: Create vectors to store the original data values and their corresponding indexes, initialized with the appropriate values.
  2. Sorting with Index Preservation: Utilize standard algorithms like std::stable_sort to arrange data by values while maintaining the correlation between the original and sorted vector indexes.
  3. Returning Sorted Indexes: Extract and return a vector containing the sorted indexes, which preserves the order of the original elements.
  4. Example Application: Use the sorted indexes in subsequent iterations to retrieve data from the original vector in the modified order.

Implementation in C 11:

#include <iostream>
#include <vector>
#include <numeric>      // std::iota
#include <algorithm>    // std::sort, std::stable_sort

using namespace std;

template <typename T>
vector<size_t> sort_indexes(const vector<T> &v) {

  // Initialize original index locations
  vector<size_t> idx(v.size());
  iota(idx.begin(), idx.end(), 0);

  // Sort indexes based on comparing values in v
  // Using std::stable_sort instead of std::sort
  // to avoid unnecessary index re-orderings
  // when v contains elements of equal values 
  stable_sort(idx.begin(), idx.end(),
       [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});

  return idx;
}
Copy after login

Example usage:

vector<double> values = {5, 2, 1, 4, 3};
vector<size_t> sorted_indexes = sort_indexes(values);

for (auto i : sorted_indexes) {
  cout << values[i] << endl;
}
Copy after login

The above is the detailed content of How Can I Preserve Original Indexes When Sorting Data in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template