Home  >  Article  >  Backend Development  >  How Can I Sort an Array of Subarrays Based on Their First Element Efficiently?

How Can I Sort an Array of Subarrays Based on Their First Element Efficiently?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-14 21:55:02315browse

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:

  1. It is more efficient than sorting the original array itself.
  2. It preserves the original order of the array.
  3. It simplifies handling complex sorting criteria.

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!

Statement:
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