AD1

Tuesday, 17 January 2017

Sorting 2D array

Assume you have 2D array of integers , int a[3][4]={8,7,6,5,
                                                                                                            -2,800,19,-40,
                                                                                                             1,-23,600,-500};

Write a C program to sort it in ascending order (from low to high)

Solution
#include <stdio.h>
int main()
{
int a[3][4]={8,7,6,5,
-2,800,19,-40,
1,-23,600,-500
};
int t=0;
int *p=&a[0];
for(int i=0;i<=12;i++)
{
for(int j=0;j<=11;j++)
{
if(*(p+j+1)<*(p+j))
{
t=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=t;
}
}
}
printf("after sorting in ascending order (from low to high) \n");
for(int i=0;i<=2;i++)
{
for(int j=0;j<=3;j++)
{
printf("%d\t",a[i][j]);
}
}
return 0;
}
view raw sort2d.c hosted with ❤ by GitHub

No comments:

Post a Comment