I'm sorting a simple, growing vector. The code works.
But the following line in which left me confused:
if (matriz[i] < matriz[j])
Why is the sign there smaller, not larger? If I want to change the positions, if the i
position is greater than the j
position, why is the sign against it?
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main()
{
int k = NULL, *matriz = NULL, aux=0;
printf("Tamanho do vetor: ");
scanf("%i", &k);
matriz = (int *)malloc(k * sizeof(int));
srand(time(0));
printf("\n");
printf("NAO ORDENADO: ");
printf("\n");
for (int i = 0; i < k; i++)
{
matriz[i] = rand() % 100;
printf("Posicao %d: %d", i + 1, matriz[i]);
printf("\n");
}
for (int i = 0; i < k; i++)
{
for (int j = 0; j < k; j++)
{
if (matriz[i] < matriz[j])
{
aux = matriz[i];
matriz[i] = matriz[j];
matriz[j] = aux;
}
}
}
printf("\n");
printf("ORDENADO: ");
printf("\n");
for (int i = 0; i < k; i++)
{
printf("Posicao %d: %d", i + 1, matriz[i]);
printf("\n");
}
printf("\n");
printf("\n");
system("pause");
return 0;
}