Question -Write a program to sort all the elements of a 4 x 4 matrix.
Solution-
It's a really good question. I have used a detailed brute force method to solve this problem. For me that's really easy to understand, but in case you can't understand or you have better method you are free to comment below.so, that's how my solution goes.
#include <stdio.h>
#include <stdlib.h>
#define m 4
#define n 4
int main()
{
int array[m][n];
int i,j,k,o,p;
printf("Enter the Elements of the array\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&array[i][j]);
}
printf("\n\n");
printf("Entered Matrix :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",array[i][j]);
printf("\n");
}
for(o=0;o<m;o++) /* Accessing the rows */
{
for(p=0;p<n;p++) /* Accessing the columns */
{
for(i=o;i<m;i++) /* Accessing row elements to compare */
{
for(j=p;j<n;j++) /* Accessing colomn elements to compare */
{
if(*(*(array+o)+p)>*(*(array+i)+j)) /* Exchanging the elements */
{
k=*(*(array+i)+j);
*(*(array+i)+j)=*(*(array+o)+p);
*(*(array+o)+p)=k;
}
}
}
}
}
printf("\n\n");
printf("Sorted Matrix :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",array[i][j]);
printf("\n");
}
getch();
}
Solution-
It's a really good question. I have used a detailed brute force method to solve this problem. For me that's really easy to understand, but in case you can't understand or you have better method you are free to comment below.so, that's how my solution goes.
#include <stdio.h>
#include <stdlib.h>
#define m 4
#define n 4
int main()
{
int array[m][n];
int i,j,k,o,p;
printf("Enter the Elements of the array\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&array[i][j]);
}
printf("\n\n");
printf("Entered Matrix :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",array[i][j]);
printf("\n");
}
for(o=0;o<m;o++) /* Accessing the rows */
{
for(p=0;p<n;p++) /* Accessing the columns */
{
for(i=o;i<m;i++) /* Accessing row elements to compare */
{
for(j=p;j<n;j++) /* Accessing colomn elements to compare */
{
if(*(*(array+o)+p)>*(*(array+i)+j)) /* Exchanging the elements */
{
k=*(*(array+i)+j);
*(*(array+i)+j)=*(*(array+o)+p);
*(*(array+o)+p)=k;
}
}
}
}
}
printf("\n\n");
printf("Sorted Matrix :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",array[i][j]);
printf("\n");
}
getch();
}
No comments:
Post a Comment