Sort 2D array in C -
i have array:
[105][2500] [110][1800] [105][800] [105][1300] [110][1200] ...
and need this:
[105][800] [105][1300] [105][2500] [110][1200] [110][1800] ...
new edit: that's code now: row nuber of rows, array 2d int array[row][2]
... (i = 0; < row; i++) printf("(%d, %d)\n", array[i][0], array[i][1]); qsort(array, row, 2*sizeof(int), compare); printf("\n sorted: \n"); (i = 0; < row; i++) printf("(%d, %d)\n", array[i][0], array[i][1]); ...
compare function:
int compare(void const *p_lhs, void const *p_rhs) { int const *lhs = (int const *) p_lhs; int const *rhs = (int const *) p_rhs; // printf("%d %d - %d %d", lhs[0], rhs[0], lhs[1], rhs[1]); if(lhs[0] < rhs[0]) return -1; if(lhs[0] > rhs[0]) return 1; if(lhs[1] < rhs[1]) return -1; if(lhs[1] > rhs[1]) return 1; return 0; }
output pritf in compare function: http://i.imgur.com/qpuxepf.png output is: http://i.imgur.com/pzk8kau.png
happily, there's qsort
in standard library. have provide comparison function elements of outer array. example:
#include <stddef.h> #include <stdio.h> #include <stdlib.h> // lexicographical comparison. // returns -1 lhs < rhs, 1 lhs > rhs, 0 lhs == rhs. int compare_line(void const *p_lhs, void const *p_rhs) { // these point elements of outer arrays (that is, // point inner arrays) double const *lhs = (double const *) p_lhs; double const *rhs = (double const *) p_rhs; if(lhs[0] < rhs[0]) return -1; if(lhs[0] > rhs[0]) return 1; if(lhs[1] < rhs[1]) return -1; if(lhs[1] > rhs[1]) return 1; return 0; } #define array_size(arr) (sizeof(arr) / sizeof*(arr)) int main(void) { double data[][2] = { { 105, 800 }, { 105, 1300 }, { 105, 2500 }, { 110, 1200 }, { 110, 1800 } }; // sorting here. qsort(data, array_size(data), sizeof(data[0]), compare_line); for(size_t = 0; < array_size(data); ++i) { printf("%lf %lf\n", data[i][0], data[i][1]); } }
Comments
Post a Comment