Home > Article > Backend Development > How Can I Sort an Array of Subarrays Based on Their First Element Efficiently?
Sorting arrays based on the first element of their subarrays poses a challenge. Rather than manipulating the array directly, consider an alternative approach.
Create an array of indices that refer to the original array. Sort the indices based on the first element of the subarrays at those indices.
This strategy has several advantages:
Here's an example in C :
#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, [&timeTable](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"; } return 0; }
Live Example
By using indices instead of manipulating the original array, you can sort complex data structures more efficiently and conveniently.
The above is the detailed content of How Can I Sort an Array of Subarrays Based on Their First Element Efficiently?. For more information, please follow other related articles on the PHP Chinese website!