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;
}
}
}
}
int. Using a 2D array (resp. pointer to a 1D array) and the index-operatorwould make this mess halfway readable.