O Quicksort escolhe um pivô, divide os valores em torno dele e repete o processo em cada parte. Aqui escolhe sempre o primeiro valor. Com partes equilibradas, o tempo é Θ(n log n). Se o pivô for sempre o menor ou o maior valor, o tempo sobe para Θ(n²). Com esta regra isso também acontece se os dados já estiverem ordenados.
Exemplo simples
Escolha 2 como o pivô. Mova 1 para a esquerda e 3 para a direita. Cada lado agora tem um item.
Início3 1 2
Resultado1 2 3
lesson.c
#include <stdbool.h>
#include <stdio.h>
int main(void) {
int values[] = {3, 1, 2};
int pivot = values[2];
int boundary = 0;
int i = 0;
while (i < 2) {
if (values[i] < pivot) {
int saved = values[i];
values[i] = values[boundary];
values[boundary] = saved;
boundary += 1;
}
i += 1;
}
values[2] = values[boundary];
values[boundary] = pivot;
i = 0;
while (i < 3) {
printf("%d\n", values[i]);
i += 1;
}
}
Saída
1
2
3
Exemplos do dia a dia
Separar encomendas por um peso de referência
Três encomendas pesam 8, 2 e 5 quilos. Use 5 como peso de referência. Que encomenda fica de cada lado?
Início8 2 5
Resultado2 • 5 • 8
Dois é mais leve e oito é mais pesado. O pivô agora separa os dois grupos.
Tratar livros com preços iguais
Cada livro custa 4. O que uma partição tridirecional produziria?
Início4 4 4
Resultado∅ • 4 4 4 • ∅
O grupo igual contém todos os livros. Nenhum grupo externo precisa de mais trabalho.
Reconhecer uma má escolha de pivô
As datas 1, 2, 3 e 4 já estão ordenadas. Se escolher sempre a última data como pivô, como ficam os grupos na primeira divisão?
Início1 2 3 4
Resultado1 2 3 • 4 • ∅
Um grupo ainda tem três itens. Repetir este padrão desperdiça comparações.
Custo e limites
Divisões equilibradas costumam exigir O(n log n) de trabalho. Escolher repetidamente um dos valores extremos como pivô pode exigir O(n²).
Complexidade temporal
Melhor caso: Θ(n log n)
Caso médio: Θ(n log n)
Pior caso: Θ(n²)
Quicksort em C
Código-fonte em C
#include<stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
while(arr[i] <= pivot && i < high) {
i++;
}
while(arr[j] > pivot && j > low) {
j--;
}
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[low] = arr[j];
arr[j] = pivot;
return j;
}
void quickSort(int arr[], int low, int high) {
if(low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
void printArray(const int arr[], size_t size) {
for(size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
printf("Before Sorting: ");
printArray(arr, SIZE);
quickSort(arr, 0, (SIZE - 1));
printf("After Sorting: ");
printArray(arr, SIZE);
return 0;
}
Saída
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anúncios
Acompanhe o exemplo passo a passo
Comece com [15, 3, 12, 6, -9, 9, 0].
Use o primeiro valor, 15, como o pivô. Examinem para dentro de ambos os lados.
Avance o índice da esquerda enquanto o valor nessa posição for menor ou igual ao pivô e o índice estiver abaixo do limite superior. Recue o índice da direita enquanto o valor nessa posição for maior do que o pivô.
Se os índices ainda não se encontraram, troque os dois valores que estão do lado errado e continue a percorrer a lista.
Quando os índices se encontram ou se cruzam, troque o primeiro valor com o valor no índice direito. O pivô está agora em sua posição final.
Recursivamente ordenar os intervalos antes e depois dessa posição. Uma faixa com menos de dois elementos já está ordenada.
Quicksort em C, passo a passo
Código-fonte em C
#include<stdio.h>
int partition(int arr[], int low, int high) {
// Pick a lowest bound element as an pivot value
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
// Increment the index value of "i"
// till the left most values should be less than or equal to the pivot value
while(arr[i] <= pivot && i < high) {
i++;
}
// Decrement the index value of "j"
// till the right most values should be greater than to the pivot value
while(arr[j] > pivot && j > low) {
j--;
}
// Interchange the values of present
// in the index i and j of an array only if i is less than j
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Interchange the element in j's poisition to the lower bound of an array
// and place the Pivot element to the j's position
arr[low] = arr[j];
arr[j] = pivot;
// Finally return the appropriate index position of the pivot element
return j;
}
void quickSort(int arr[], int low, int high) {
if(low < high) {
// Find the pivot index of the lower bound of an array
int pivot = partition(arr, low, high);
// Apply Divide and conquer strategy
// to sort the left side and right side of an array
// respective to the pivot position
// Left hand side array
quickSort(arr, low, pivot - 1);
// Right hand side array
quickSort(arr, pivot + 1, high);
}
}
void printArray(const int arr[], size_t size) {
// Loop the item and print each item in the console with white space seperated
for(size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
printf("Before Sorting: ");
printArray(arr, SIZE);
quickSort(arr, 0, (SIZE - 1));
printf("After Sorting: ");
printArray(arr, SIZE);
return 0;
}
Saída
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15