Error showing results - URI 1566

Asked

Viewed 186 times

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;
}

1 answer

2


I think the problem is here:

       printf("%d ", vetor[j]);

This space at the end will mess up the automatic check of the code output. Try to do so:

       if (z != 0) printf(" ");
       printf("%d", vetor[j]);

With this, you get to have the spaces before the number, only if it is not the first, which should fix this problem.

Maybe the printf("\n"); can give a similar problem as well. The solution would also be to put a if therein.

  • Look I did what you told, only I think because of this if, the time has stopped

  • 3

    @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.

  • 2

    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

  • 2

    Type, if (num > 0) { printf("%d", vetor[0]); for (int j = 1;...) { printf(" %d", vetor[j]); }

  • With help from @Jefferson Quesado, the code has passed, thank you Victor and Jefferson Quesado for their help

Browser other questions tagged

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