Home > Backend Development > C++ > body text

How to Sort an Array of Arrays by the First Element in C ?

Barbara Streisand
Release: 2024-11-21 19:05:13
Original
954 people have browsed it

How to Sort an Array of Arrays by the First Element in C  ?

How to Sort an Array of Arrays by the First Element?

You have an array of arrays, such as [[4, 204], [10, 39], [1, 500]]. You want to sort them by the first element of the subarray to get [[1, 500], [4, 204], [10, 39]]. Here's how to do it in C :

Approach: Sorting Indices Instead of Arrays

Rather than sorting the array itself, you can sort an array of indices that point to the original array. This approach is more efficient for large arrays where each subarray contains a significant amount of data or when the original order needs to be preserved.

Step 1: Create an Index Array

Initialize an array of indices named index, where the indices range from 0 to n-1, where n is the number of subarrays.

Step 2: Define a Sorting Predicate

Create a sorting predicate that compares the first elements of the subarrays using the index array. The predicate should return true if the first element of the subarray at index n1 is less than that at index n2.

bool compareFirstElement(int n1, int n2) {
  return timeTable[n1][0] < timeTable[n2][0];
}
Copy after login

Step 3: Sort the Index Array

Sort the index array using the std::sort function and the defined predicate. This will rearrange the indices to be in ascending order based on the first elements of the subarrays.

std::sort(index, index + 3, compareFirstElement);
Copy after login

Step 4: Use Sorted Indices to Access Data

To access the sorted data, use the sorted index array to point to the subarrays in the timeTable array.

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

Live Example:

[Live Example](https://wandbox.org/permlink/sXTyuT2fubLi4j7i)

Note: This approach can also be applied to sort arrays of objects or structs that contain sortable data.

The above is the detailed content of How to Sort an Array of Arrays by the First Element 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