Home > Backend Development > C++ > body text

How to Sort a 2D Array in C Using qsort()?

Susan Sarandon
Release: 2024-11-05 06:53:02
Original
369 people have browsed it

How to Sort a 2D Array in C   Using qsort()?

Sorting a 2D Array in C Using qsort()

When faced with the task of sorting a 2D array, one may consider utilizing built-in functions to simplify the process. In C , the qsort() function stands out as a powerful tool for this purpose. Unlike its counterpart, sort(), qsort excels in handling multiple-column sorting for fixed arrays.

The comparator function in qsort() takes a unique approach, utilizing a series of ternary statements to compare elements effectively. The result is an algorithm that adeptly handles sorting arrays based on specific column values.

Consider the following example, where a 2D array is populated with random data and requires sorting based on its first column:

<code class="cpp">#include <iostream>
#include <random>
#include <algorithm>

int main() {
    int ar[10][2];

    // Populate array with random data
    std::random_device rd;
    std::default_random_engine rng(rd());
    std::uniform_int_distribution<> dist(1, 20);
    std::for_each(std::begin(ar), std::end(ar), [&](int(&ar)[2]) { ar[0] = dist(rng); ar[1] = dist(rng); });

    // Sort the array
    std::qsort(ar, 10, sizeof(*ar),
        [](const void *arg1, const void *arg2) -> int {
            int const *lhs = static_cast<int const *>(arg1);
            int const *rhs = static_cast<int const *>(arg2);
            return (lhs[0] < rhs[0]) ? -1
                : ((rhs[0] < lhs[0]) ? 1
                : (lhs[1] < rhs[1] ? -1
                : ((rhs[1] < lhs[1] ? 1 : 0))));
        });

    // Display sorted array
    std::for_each(std::begin(ar), std::end(ar), [](const int(&ar)[2]) { std::cout << ar[0] << ',' << ar[1] << '\n'; });

    return 0;
}</code>
Copy after login

In this sample, the comparator ensures that the first column values are compared diligently to achieve the desired sorting. By leveraging qsort() and tailoring the comparator to suit your specific needs, you can efficiently sort 2D arrays in C , making data manipulation a breeze.

The above is the detailed content of How to Sort a 2D Array in C Using qsort()?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!