Learning C and this is an exercise.
The user is asked to input the dimension of an two-dimensional array.
Then the user inputs the values of that array.
Finally, the program must be able to sort every line from the lowest to the greatest and print the result.
For instance
input:
2 2
13 11
13 11
Should print:
11 13
11 13
But my program is printing:
11 13
13 11
If in my code I declare a fixed array size, lets say matrix[2][2] and change all the code to that array dimension, the program works great but if I declare matrix[MAX][MAX], since I don know what would be the size of the array, it gives me the output I’ve posted above.
Is this because I’m not using pointers and memory allocation? (Remember that I’m still learning C).
Here is the code I’ve done:
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
/*Print the final two-dimensional array*/
void print( int a[MAX][MAX], int b[])
{
int i,j;
for (i=0; i<b[0]; i++)
{
for (j=0; j<b[1]; j++)
{
printf("%d", a[i][j]);
if (j < b[1]-1)
{
printf(" ");
}
}
printf("\n");
}
}
/* Sort my array */
int Qsort (int v[MAX][MAX], int li, int ls)
{
int j;
if (li < ls)
{
j = order(v,li, ls);
Qsort (v, li, j-1);
Qsort (v, j+1, ls);
}
return v[MAX][MAX];
}
int order(int x[], int li, int ls)
{
int a, down, up, temp;
a=x[li]; down=li; up=ls;
while (down<up)
{
while (x[down]<=a && down<ls)
down ++;
while (x[up]>a)
up --;
if (down < up)
{
temp=x[down];
x[down]=x[up];
x[up]=temp;
}
}
x[li]=x[up];
x[up]= a;
return up;
}
int main()
{
int i,j,size,jump,jump2;
int tam[2];
int matrix[MAX][MAX];
/*Define rows and columms*/
i=0;
while (i<2)
{
scanf("%d", &tam[i]);
i++;
}
/*Fill the array with the numbers the user inputs*/
for (i=0; i<tam[0]; i++)
{
for (j=0; j<tam[1]; j++)
{
scanf("%d", &matrix[i][j]);
}
}
size = tam[1];
jump = 1;
jump2 = 0;
for(i=0;i<tam[0];i++)
{
Qsort (matrix,jump2, jump*size-1);
jump++;
jump2 = jump2 + size;
}
print (matrix,tam);
return 0;
}
Thanks,
Favolas
It looks like you are sorting the first row over and over. You only want to pass a single column to
Qsortso it should be declared:In your main function, simply call Qsort with each successive row: