Reputation: 527
Many colleagues of mine were asking me if it is possible to sort each row of a 2D-Array, by using the function qsort()
from <stdlib.h>
to arrange a matrix like:
5, 8, 7, 6, 1, 4, 3, 2, 11, 12, 10, 9,
into something like:
5, 6, 7, 8, 1, 2, 3, 4, 9, 10, 11, 12,
Upvotes: 2
Views: 2279
Reputation: 589
Patrick,
Imagine the 2d array as a combination of many 1d arrays.
Perform a sort on each of the 1d arrays(rows), using 2 loops. One loop to iterate through the (columns) and one though the 1d arrays. In the second inner loop you can perform sorting.
Upvotes: 0
Reputation: 527
The solution to the problem looks like the following:
#include <stdio.h> // scanf() printf()
#include <stdlib.h> // qsort()
int compare (const void *a, const void *b)
{
int x = *(int *)a;
int y = *(int *)b;
if (x<y) return -1;
if (x>y) return 1;
return 0;
}
int main()
{
// Syntax of a 2D Array: array[rows][cols]
int rows = 3, cols = 4;
int array[3][4] = { {5,8,7,6,}, {1,4,3,2}, {11,12,10,9} };
// Print the matrix unsorted:
printf("\nUnsorted rows:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%2d, ", array[i][j]);
}
printf("\n");
}
// Sort the matrix using qsort:
for(int j = 0; j < rows; j++)
qsort(array[j], cols, sizeof(int), compare);
// Print the matrix sorted:
printf("\nSorted rows:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%2d, ", array[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Unsorted rows: 5, 8, 7, 6, 1, 4, 3, 2, 11, 12, 10, 9, Sorted rows: 5, 6, 7, 8, 1, 2, 3, 4, 9, 10, 11, 12,
Thanks to flukey for the helpful answer in: Qsorting 2d pointer arrays
Upvotes: 1