Search code examples
cpointersmultidimensional-arraybubble-sort

Sorting elements in a row in a 2 dimensional array using pointers


I am trying to sort a row of 2 dimensional array. But I am unable to achieve it.

For eg:

    7 6 5
    5 7 6
    8 2 9
    2 3 4

to be like this:

    5 6 7
    5 6 7
    2 8 9
    2 3 4

Below is my code:

void sort(int *a,int num){
    int i,j,temp;
    for(i=0;i<num-1;i++){
        for (j=0;j<num-i-1;j++){
            if (*((a+i*3)+j)>*((a+i*3)+j+1)){
                temp=*((a+i*3)+j);
                *((a+i*3)+j)=*((a+i*3)+j+1);
                *((a+i*3)+j+1)=temp;
            }
        }
    }

    for(i=0;i<num;i++){
        for(j=0;j<3;j++)
            printf("%d ",*((a+i*3)+j));
        printf("\n");
        }
}

Output of the above code:

    6 5 5 
    7 6 7 
    2 8 9 
    2 3 4

Can anyone tell what's the problem in the code? Thanks in advance. :D

EDIT: So should the above code look like this?

    void sort(int *a,int num){
    int i,j,temp;
    for(i=0;i<num-1;i++){
        for (j=0;j<num-i-1;j++){
            if (*(*(a+i)+j)>*(*(a+i)+j+1)){
               temp=*(*(a+i)+j);
               *(*(a+i)+j)=*(*(a+i)+j+1);
               *(*(a+m)+j+1)=temp;
            }
        }
    }
}

Solution

  • The code is too complicated, so you did many small mistakes in it.

    You should separate sorting of each row somehow, like this:

    for (row = 0; row < num; row++) {
        sort_row(a + row * 3);
    }
    

    The function sort_row sorts just one row, so it's going to be easier to write and test (BTW I replaced the nondescript name i by row).

    The function sort_row should do normal bubble sort. You can even use the standard library qsort instead (for purposes of testing).

    Note that standard bubble-sort algorithm is implemented with two nested loops. If you want to implement your code without a separate sort_row function call, you will need three nested loops.