Home  >  Article  >  Backend Development  >  How to Sort an Array of Subarrays by the First Element in C ?

How to Sort an Array of Subarrays by the First Element in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 00:18:12853browse

How to Sort an Array of Subarrays by the First Element in C  ?

Sorting Arrays by First Item in Subarrays in C

Original arrays consist of subarrays with two elements: e.g., [[4, 204], [10, 39], [1, 500]]. The goal is to sort these arrays based on the first element of each subarray: [[1, 500], [4, 204], [10, 39]].

Sorting Technique

Interestingly, it's not necessary to manipulate the original array itself. Instead, a better approach is to sort an array of indices that point to the subarrays within the original array, and then use the sorted indices to access the sorted elements.

Benefits of this Technique

Sorting indices instead of the original array is advantageous when:

  • The original array elements are large in size.
  • The original order of the array needs to be preserved.
  • The original array is awkward or impossible to manipulate efficiently in a sorting algorithm.

Example Implementation

Consider the following example code:

#include <algorithm>
#include <iostream>

int main() {
    int index[3] = {0, 1, 2};
    int timeTable[3][2] = {{4, 204}, {10, 39}, {1, 500}};
    std::sort(index, index + 3, [&amp;](int n1, int n2) {
        return timeTable[n1][0] < timeTable[n2][0];
    });

    for (int i = 0; i < 3; ++i) {
        std::cout << "The index is " << index[i] << ". The data at this index is ["
                  << timeTable[index[i]][0] << " " << timeTable[index[i]][1] << "]\n";
    }
}

In this example:

  • index is an array of indices initialized with values 0, 1, and 2.
  • timeTable is the original array of subarrays.
  • std::sort is used to sort index based on the first element of the corresponding subarray in timeTable.
  • After sorting the indices, the sorted subarrays can be accessed using the sorted index array, as shown in the for loop.

Note: This sorting technique is applicable not only to arrays of subarrays but also to scenarios where multiple arrays need to be sorted in parallel based on data from one of the arrays.

The above is the detailed content of How to Sort an Array of Subarrays by the First Element in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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