Sorting Multi-Dimensional Arrays by Subarray First Element in C
To sort a multi-dimensional array by the first element of each subarray, it's recommended to adopt an indirect sorting approach rather than directly manipulating the array. This involves creating an array of indices that point to the original array and sorting the indices based on the desired criteria.
Implementation
Here's an example implementation in C :
#include <algorithm> int main() { // Sample array of arrays int timeTable[3][2] = {{4, 204}, {10, 39}, {1, 500}}; // Create an array of indices to use for sorting int indices[3] = {0, 1, 2}; // Sort indices based on the first element of each subarray in timeTable std::sort(indices, indices + 3, [](int i1, int i2) { return timeTable[i1][0] < timeTable[i2][0]; }); // Access the sorted subarrays using the sorted index array for (int i = 0; i < 3; ++i) { std::cout << "Subarray at index " << indices[i] << ": [" << timeTable[indices[i]][0] << ", " << timeTable[indices[i]][1] << "]" << std::endl; } }
Example
For the sample array timeTable, the output would be:
Subarray at index 0: [1, 500] Subarray at index 1: [4, 204] Subarray at index 2: [10, 39]
Benefits of Indirect Sorting
This indirect sorting method offers several advantages over direct sorting:
The above is the detailed content of How to Sort a Multi-Dimensional Array by the First Element of Each Subarray in C ?. For more information, please follow other related articles on the PHP Chinese website!