Sort a matrix in C

Asked

Viewed 3,516 times

1

I’m trying to sort an array in C. The logic I used would be to create an array size, copy the values there, sort the values and then copy them to the array again. To do this I use a function that receives as parameters the dimensions of the matrix and its address (manipulation by pointers). But when I go to copy to the vector, the stored values are other totally different.

int ordenaMatriz(int **matriz, int lin, int col){

int i, j, menor, cont=0, indice;
int vetor[lin*col]; 

for(i=0;i<lin;i++){
    for(j=0;j<col;j++){
        vetor[cont]=matriz[i][j];
        cont++;
    }
}

for(i=0;i<(lin*col);i++){
    printf("%d ", vetor[cont]);
}
for(i=0;i<lin*col;i++){
    menor=vetor[i];
    for(j=0;j<lin*col;j++){
        if(vetor[j]<menor){
            menor=vetor[j];
            int aux = vetor[i];
            vetor[i] = menor;
            vetor[j] = aux;
        }
    }
}
for(i=0;i<lin;i++){
    for(j=0;j<col;j++){
        matriz[i][j]=vetor[cont];
        cont++;
    }
}

}

Main

int main(int argc, char** argv) {
int lin, col, i;
int **matriz;

printf("Digite as dimensoes da matriz: ");
scanf("%d %d", &lin, &col);

alocaMatriz(&matriz, lin, col);
leMatriz(matriz, lin, col);
mostraMatriz(matriz, lin, col);
ordenaMatriz(matriz, lin, col);
printf("\n\nMatriz ordenada:\n\n");
mostraMatriz(matriz, lin, col);
desalocaMatriz(&*matriz, lin, col);

return 0;
}
  • Look at this https://answall.com/q/232895/101. Why is so many copies? it is possible to make without any copies. It gets a little easier making a copy, but so many don’t know why. You have difficulties that arise because the algorithm is too complex. Anyway, I think there’s information missing so we can help. Basically, you’re saying there’s a mistake and we turn around to find it. There are syntax errors in this code.

  • Check what matrix[i][j] means when you set it to **matrix.

1 answer

1


Sorting function has two problems.

One is merely visual, the part where you print the copy before ordering:

for(i=0;i<(lin*col);i++){
    printf("%d ", vetor[cont]);
}

Notice that it’s showing vetor[cont] instead of vetor[i], whereas i is the variable of for. But this problem is only in printing does not affect the ordering itself.

Then in the replacement of the values in the original matrix it failed to start the cont to 0 again:

for(i=0, cont = 0 /*<= faltava este*/; i<lin; i++ /*O cont++ também podia ficar aqui*/)
{
    for(j=0; j<col; j++)
    {
        matriz[i][j]=vetor[cont];
        cont++;
    }
}

This gives you the result you expect

That you can see in Ideone

You could also sort without creating the auxiliary vector but it would make the code more complex, requiring 4 for since every 2 for run through the matrix from start to finish.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.