How do I show the randomized quicksort step by step?

Asked

Viewed 133 times

0

How do I show the sort process step by step? Either by showing the state of the vector at each change or by showing a tree. I have tried to print each of the three functions and also tried to create a function, but the results only got worse.

#include <stdio.h>
#include <stdlib.h>
void swap(int A[], int i, int j){
    int temp = A[i];
    A[i] = A[j];
    A[j] = temp;
}
int partition(int A[], int inicio, int fim) {
    int k;
    double d;
    d = (double) rand () / ((double) RAND_MAX + 1);
    k = d * (fim - inicio + 1);
    int randomIndex = inicio + k;
    swap(A, randomIndex, fim);
    //*******************ALGORITMO DE PARTIÇÃO DE CORMEN*********************
    //o pivo é o elemento final
    int pivo = A[fim];
    int i = inicio - 1;
    int j;
    /*
     * Este laço irá varrer os vetores da esquerda para direita
     * procurando os elementos que são menores ou iguais ao pivô.
     * Esses elementos são colocados na partição esquerda.
     */
    for (j = inicio; j <= fim - 1; j++) {
        if (A[j] <= pivo){
            i = i + 1;
            swap(A, i, j);
        }
    }
    swap(A, i + 1, fim);
    return i + 1; //retorna a posição do pivô
}
//Quicksort de Cormen
void quicksortAleatorizado(int A[], int inicio, int fim) {
    if (inicio < fim) {
        //realiza a partição
        int q = partition(A, inicio, fim);
        //ordena a partição esquerda
        quicksortAleatorizado(A, inicio, q - 1);
        //ordena a partição direita
        quicksortAleatorizado(A, q + 1, fim);
    }
}
int main(int argc, char const *argv[])
{
    int vetor[] = {6, 8, 5, 3, 2, 1, 4, 7, 9, 10};
    int n = 10;
    quicksortAleatorizado(vetor, 0, n);
    for(int i=0;i<n;i++){
        printf("%d ", vetor[i]);
    }
    return 0;
}
  • A print inside the function swap would not be enough?

1 answer

0

Unlike higher-level languages, such as Python and Javascript, which can take any type of data and turn it into something readable to the user when printing, in C the only way to display the data properly is by assembling its own display algorithm. If you want to show the data in tree form, you will have to assemble your own function to display the program matrix in tree format, this holds for any format you want to display the data.

Browser other questions tagged

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