Home >Backend Development >C++ >How do I sort a 2D array in C using built-in functions or custom methods?
Sorting a 2D Array in C with Built-In Functions or Alternate Methods
Sorting a 2D array in C presents a unique challenge, as built-in functions such as std::sort() are typically designed for 1D arrays. However, there are specific cases where you may want to sort a 2D array based on specific criteria, such as comparing the first column values only.
Utilizing std::qsort
While C lacks a direct built-in function for multi-column sorting, std::qsort() offers a versatile solution. This function takes a pointer to an array, the size of the array, the size of elements within the array, and a comparison function. By providing a custom comparison function, you can specify the sorting criteria based on specific array elements.
Comparator Function for Custom Sorting
The comparison function must return an integer result based on the comparison of two array elements. In the case of a 2D array, you would need to access individual elements using pointer arithmetic. Consider the following example:
<code class="cpp">int qsort_compare(const void *arg1, const void *arg2) { 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)))); }
This comparator function compares the first element (equivalent to the first column value) and returns an appropriate ordering based on the result.
Example Implementation
Combining std::qsort() and the custom comparison function, you can sort a 2D array in C as follows:
<code class="cpp">#include <iostream> #include <algorithm> using namespace std; int main() { int ar[5][2] = { {20, 11}, {10, 20}, {39, 14}, {29, 15}, {22, 23} }; qsort(ar, 5, sizeof(*ar), qsort_compare); cout << "Sorted 2D Array:" << endl; for (int i = 0; i < 5; i++) { cout << ar[i][0] << " " << ar[i][1] << endl; } return 0; }</code>
Output:
Sorted 2D Array: 10 20 20 11 22 23 29 15 39 14
This method provides a comprehensive and efficient solution for sorting 2D arrays in C , although it requires the creation and use of a custom comparison function.
The above is the detailed content of How do I sort a 2D array in C using built-in functions or custom methods?. For more information, please follow other related articles on the PHP Chinese website!