Search code examples
carraysrandombubble-sort

Bubble sort 2D array in C


I need a function to bubble sort this randomly generated 2D array. Also with rand() method I wanted it to generate numbers between (1, 1000000) but it doesnt give the required range, any suggestion to find out a solution?

int **matrix()
{

    int **matrix;
    int row, column;
    long s, k;
    int i,j,f,swap;


    srand(time(NULL));
    printf("Number of rows: ");
    scanf("%d", &row);

    printf("Number of column: ");
    scanf("%d", &column);


    matrix = (int **) calloc(row, sizeof(int));


    for(i = 0; i < row; i++)
        matrix[i] = (int *) calloc(column, sizeof(int));


    for(s = 0; s < row; s++)
    {
        for(k = 0; k < column; k++)
        {

            matrix[s][k]=rand()%10000000;
        }
    }

    for(s = 0; s < row; s++)
    {
        for(k = 0; k < column; k++)
            printf("%4d \t\t", matrix[s][k]);

        printf("\n");
    }


    for(i = 0; i < row; i++)
        free((void *) matrix[i]);


    free((void *) matrix);

    return **matrix;

}

Solution

  • Sorting a 2D array with bubble sort is a little different that sorting a single dimensional array. This example may help with that part of your question.

    Other issues:

    Based on this section:

    for(i = 0; i < row; i++)
         matrix[i] = (int *) calloc(column, sizeof(int));
    

    The line in the preceding section:

     matrix = (int **) calloc(row, sizeof(int));
                                            ^
    

    Should be allocating memory for int *

     matrix = calloc(row, sizeof(int *));
                                     ^
    

    (Note the cast for calloc() has also been removed. In C casting the return of [c][m][re]alloc is not recommended.)

    Also with rand() method I wanted it to generate numbers between (1, 1000000) but it doesnt give the required range, any suggestion to find out a solution?

    ( With credit to this answer )

    rand() expanded to provide a pseudo random distribution of 1000000 unique values:

    unsigned long rand_ex(void);
    
    int main(void){
    
        srand(clock());
        for(int  i=0;i<100;i++)
        {
            printf("%10d:  %10lu\n", i, rand_ex());
        }
        return 0;
    }
    
    unsigned long rand_ex(void)
    {     
        unsigned long x;
        x = rand();
        x <<= 15;
        x ^= rand();
        x %= 1000001;
    
        return x;
    }