Home > Article > Backend Development > 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:
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, [&](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:
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!