1

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;
            }
        }
    }
}
1
  • There is no 2D array. Just a pointer to int. Using a 2D array (resp. pointer to a 1D array) and the index-operatorwould make this mess halfway readable. Commented Jul 23, 2017 at 17:28

2 Answers 2

2

There are two main problems:

1) the loops are not running for n times, Hence the condition in for loop should be changed to i < num instead of i < num - 1 which skips the last row

2) From your code it seems you want to use bubble sort technique. The sort is O(n^2) and that's why require the swapping if statement to run (n - 1)times for each element, hence you should include one more for loop inside the j-for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh! Thank you very much...didn't think for the another loop. Thx once again. :D
1

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.

1 Comment

Thx, anatolyg I will keep in mind to use library function next time... :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.