Sort 2D matrix in C

有些话、适合烂在心里 提交于 2019-12-13 23:21:33

问题


I am new to programming in C, and have but one problem that I can't seem to figure out on my own.

I have created a 2-dimensional matrix and need to sort all 100 randomly generated numbers in the matrix using bubble sort. I also need to save the output for later use in my program. Has anybody got any idea?

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

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

    // Generate random numbers in a matrix
    printf("Numbers generated:\n");
    srand((int)time(NULL));
    for(i=0; i<10; i++) {
        for(j=0; j<9; j++) {
            matrix[i][j] = (rand()%900) + 100;
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
    // Sort matrix
    for(i=0; i<10; i++) {
        for(j=0; j<10; j++) {
            // Sort algorithm goes here
        }
    }
    // Present sorted matrix
    printf("\nSorted matrix:\n");
    for(i=0; i<10; i++) {
        for(j=0; j<9; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
    return 0;
}

I would be most thankful for an answer!


回答1:


#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;
    }
}


来源:https://stackoverflow.com/questions/27267326/sort-2d-matrix-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!