What’s wrong with my Quicksort code in C?

Asked

Viewed 112 times

0

Here is my code:

#include <stdio.h>
#include <stdlib.h>

int lista[1000];
int tamanho;
main () {
  printf("Tamanho: ");
  scanf("%d", & tamanho);
  int c;
  for (c = 0; c < tamanho; c++) {
    lista[c] = c + 1;
  }
  misturar();
  for (c = 0; c < tamanho; c++) {
    printf("%d ", lista[c]);
  }
  quick(lista, 0, tamanho - 1);
}
misturar() {
  int a,b,backup;
  for (a = 0; a < tamanho; a++) {
    b = rand() % tamanho;
    backup = lista[a];
    lista[a] = lista[b];
    lista[b] = backup;
  }
}
quick(int *tabela, int ini, int fim) {
  int a,b,pivo,backup;
  a = ini;
  b = fim;
  pivo = tabela[(a + b) / 2];
  while (a < b) {
    while (tabela[a] < pivo) {
      a = a + 1;
    }
    while (tabela[b] > pivo) {
      b = b + 1;
    }
    if (a <= b) {
      backup = tabela[a];
      tabela[a] = tabela[b];
      tabela[b] = backup;
      a = a + 1;
      b = b - 1;
    }
  }
  if (b > ini) {
    quick(*tabela, ini, b - 1);
  }
  if (a < fim) {
    quick(*tabela, a, fim - 1);
  }
}

My compiler is Code Blocks, That is the result Esse é o resultado

  • So you don’t always generate the same random numbers, do it srand(time(NULL)); right at the start of your job main(). Remember to do #include <time.h>.

2 answers

1

So at first glance I detected two errors (I did not compile or run your code):

the b has to go backwards

    while (tabela[b] > pivo) {
      // b = b + 1; // OOPS
      b = b - 1;
    }

and to call the function quick() recursively you have to use the correct paramatron

  if (b > ini) {
    // quick(*tabela, ini, b - 1);
    quick(tabela, ini, b - 1);
  }
  if (a < fim) {
    // quick(*tabela, a, fim - 1);
    quick(tabela, a, fim - 1);
  }

Tip: turn on as many warnings as possible from your compiler and pay attention to them. The compiler must warn you in recursive call (the indexing error with b is not caught by warnings).

  • Thanks for the errors you noticed, but my quicksort is still not working, how do I turn on the Warning alert at most?

-1

You are doing things in the wrong order, the right one would be: mix >> sort >> print;

Or you could do so: mix >> printar >> sort >> printar;

Browser other questions tagged

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