Home >Backend Development >C++ >How to Sort an Array of Arrays by the First Element of Each Subarray in C ?
Sorting an Array of Arrays by First Item in Subarray in C
Given an array of arrays, the task is to sort them based on the first element of each subarray. Consider an array like [[4, 204], [10, 39], [1, 500]]. After sorting, it should become [[1, 500], [4, 204], [10, 39]].
Approach Using Index Sorting:
Instead of directly sorting the array, a more efficient method is to sort an array of indices pointing to the subarrays. This eliminates the need for complex manipulation of the original array in the sorting function.
Here's an example code implementation:
#include <algorithm> #include <iostream> int main() { int index[3] = {0, 1, 2}; int timeTable[3][2] = {{4, 204}, {10, 39}, {1, 500}}; // Sort the indices based on the first item of each subarray std::sort(index, index + 3, [&](int n1, int n2) { return timeTable[n1][0] < timeTable[n2][0]; }); // Iterate over the sorted indices and access the corresponding subarrays for (int i = 0; i < 3; ++i) { std::cout << "The index is " << index[i] << ". The data at this index is ["; std::cout << timeTable[index[i]][0] << " " << timeTable[index[i]][1] << "]\n"; } return 0; }
In this snippet, we create an index array and sort it using a custom sorting criteria that compares the first elements of the subarrays at indices n1 and n2. After sorting, we can access the sorted subarrays through the reordered index array.
The above is the detailed content of How to Sort an Array of Arrays by the First Element of Each Subarray in C ?. For more information, please follow other related articles on the PHP Chinese website!