Home > Backend Development > C++ > body text

How to Sort a Multi-Dimensional Array by the First Element of Each Subarray in C ?

Barbara Streisand
Release: 2024-11-25 21:58:15
Original
918 people have browsed it

How to Sort a Multi-Dimensional Array by the First Element of Each Subarray in C  ?

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;
    }
}
Copy after login

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]
Copy after login

Benefits of Indirect Sorting

This indirect sorting method offers several advantages over direct sorting:

  • Memory Efficiency: It does not require additional storage space for a temporary copy of the original array.
  • Performance: Sorting indices is generally faster than directly manipulating the original array.
  • Flexibility: It is easier to change the sorting criteria, as it only involves modifying the sorting predicate in the std::sort call.
  • Maintainability: The code is more readable and maintainable, as it avoids complex operations on multi-dimensional arrays.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template