Hello I have a bidimensional array initiated the following way:
#include <stdio.h>
#include <stdlib.h>
int main(){
char matriz[6][5]={
{'F','H','V','D','U'},
{'E','L','Q','U','E'},
{'P','E','R','S','E'},
{'V','E','R','A','A'},
{'L','C','A','N','Z'},
{'A','Z','Z','Z','Z'}};
system("pause");
}
And I need to move the columns, ordering alphabetically the first line,
I mean, the line that contains {'F','H','V','D','U'}
.
I need the following output:
char matriz[6][5]={
{'D','F','H','U','V'},
{'U','E','L','E','Q'},
{'S','P','E','E','R'},
{'A','V','E','A','R'},
{'N','L','C','Z','A'},
{'Z','A','Z','Z','Z'}};
I know I need to use the selective ordering method and a cycle of fors, but I am not sure how.
First you have to compare the first elements of each column to all other top elements,if a column's 1st element is greater than the next column's top element then swap both columns.You can also use qsort function in the algorithm header for sorting.
Below is the implementation:
#include <stdio.h>
int main(){
int i,k,j;
char matriz[6][5]={
{'F','H','V','D','U'},
{'E','L','Q','U','E'},
{'P','E','R','S','E'},
{'V','E','R','A','A'},
{'L','C','A','N','Z'},
{'A','Z','Z','Z','Z'}};
for(i=0;i<4;i++)
{
for(k=i+1;k<5;k++)
{
//comparing top elements of columns
if(matriz[0][i]>matriz[0][k])
{
//swapping columns
for(j=0;j<6;j++)
{
int t=matriz[j][i];
matriz[j][i]=matriz[j][k];
matriz[j][k]=t;
}
}
}
}
//display
for(i=0;i<6;i++)
{
for(k=0;k<5;k++)
printf("%c ",matriz[i][k]);
printf("\n");
}
}