What's wrong with my QuickSort C code?

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, This is the result

    
asked by anonymous 28.08.2016 / 17:58

2 answers

1

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

b has to walk 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 paramater

  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 the maximum warnings from your compiler and pay attention to them. The compiler has to warn you in the recursive call (the error of indexing with b is not caught by warnings).

    
29.08.2016 / 11:46
-1

You're doing things in the wrong order, the right one would be: mix > > sort > > printar;

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

    
28.08.2016 / 18:17