1
I made as a request URI problem 1566, only it’s giving presentation error, and I don’t know how to fix.
Just follow my code:
#include <stdio.h>
#include <stdlib.h>
int ordena(const void *a, const void *b);
int main(int argc, char** argv)
{
int teste, num;
scanf("%d", &teste);
for(int i = 0; i < teste; i++)
{
scanf("%d", &num);
int vetor[num];
for(int j = 0; j < num; j++)
{
scanf("%d", &vetor[j]);
}
qsort(vetor, num, sizeof(int), ordena);
for(int j = 0; j < num; j++)
{
printf("%d ", vetor[j]);
}
printf("\n");
}
return 0;
}
int ordena(const void *a, const void *b)
{
if(*(int*)a == *(int*)b)
return 0;
else if(*(int*)a < * (int*)b)
return -1;
else
return 1;
}
Look I did what you told, only I think because of this if, the time has stopped
– rafael marques
@rafaelmarques Ah, if the time has expired it was something else: Quicksort has performance O(n log n) in the AVERAGE. But in the worst case, the quicksort is O(n²). The URI test must have placed some entries that generate the worst case. The solution to this is to use another sort algorithm, such as mergesort, which is always O(n log n) even in the worst case.
– Victor Stafusa
There is another less elegant way to put space conditionally, but without having to generate branches execution. Hypothetically the compiler could detect this for you as well. This is the case of extracting the first element and printing us with the space before the number. This keeps the same amount of calls to
printf
practically and avoids conditional execution– Jefferson Quesado
Type,
if (num > 0) { printf("%d", vetor[0]); for (int j = 1;...) { printf(" %d", vetor[j]); }
– Jefferson Quesado
With help from @Jefferson Quesado, the code has passed, thank you Victor and Jefferson Quesado for their help
– rafael marques