Sort 2D matrix in C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

void bubble_sort(void *base, size_t n, size_t size,
                 int (*cmp)(const void*, const void *));

int cmp_int(const void *a, const void *b){
    int x = *(const int *)a;
    int y = *(const int *)b;
    return x < y ? -1 : x > y;
}

int main() {
    int i, j, matrix[10][10];

    // Generate random numbers in a matrix
    printf("Numbers generated:\n");
    srand((unsigned)time(NULL));
    for(i=0; i<10; i++) {
        for(j=0; j<10; j++) {
            matrix[i][j] = rand()%900 + 100;
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
    // Sort matrix
    for(i=0; i<10; i++) {
        bubble_sort(matrix[i], 10, sizeof(**matrix), cmp_int);//sort column of row
    }
    bubble_sort(matrix, 10, sizeof(*matrix), cmp_int);//sort row by 1st column.
    // Present sorted matrix
    printf("\nSorted matrix:\n");
    for(i=0; i<10; i++) {
        for(j=0; j<10; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
    return 0;
}

void swap(void *a, void *b, size_t size){
    void *temp = malloc(size);
    memcpy(temp, a   , size);
    memcpy(a   , b   , size);
    memcpy(b   , temp, size);
    free(temp);
}

void bubble_sort(void *base, size_t n, size_t size, int(*cmp)(const void*, const void *)){
    for(; n>0; --n){
        int i, swaped = 0;
        for(i=0; i<n-1; ++i){
            void *a = (char*)base + i*size;
            void *b = (char*)base + (i+1)*size;
            if(cmp(a, b)>0){
                swap(a, b, size);
                swaped = 1;
            }
        }
        if(!swaped)
            break;
    }
}

Leave a Comment