Sort an array in C

1

I am trying to sort an array in C. The logic I used would be to create a vector with the size of the array, copy the values there, sort the values, and then copy to the array again. To do this I use a function that receives as parameters the dimensions of the array and its address (manipulation through pointers). But when I go to make the copy to the vector, the stored values are 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;
}
    
asked by anonymous 09.09.2017 / 14:58

1 answer

1

The sort 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 you are displaying vetor[cont] instead of vetor[i] , with i being the for variable. But this problem is only in print does not affect the ordering itself.

Then, when you reset the values in the original array, you were prompted to start 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 already gives you the result you expect

What you can see on Ideone

You could also sort without creating the helper vector but would make the code more complex, requiring 4 for since every 2 for runs through the array from start to finish.

    
09.09.2017 / 16:23