Algoritmi C/C++

Quick Sort

Quick sort posiziona il pivot e ordina ricorsivamente le partizioni.

Che cos’è Quick Sort?

Quick sort posiziona il pivot e ordina ricorsivamente le partizioni.

Partiziona i valori intorno a un pivot.

Punti importanti

  • Testa input vuoti, singoli, duplicati e ordinati.
  • Separa correttezza e ottimizzazione.
  • Preferisci la standard library in produzione.

Visualizzatore di Quick Sort

O(n log n)

Usa Avvia o Passo per seguire ogni confronto e spostamento dei dati.

Esempi di codice C e C++

C
Esegui →
main.c
#include <stdio.h>

void swap(int *left, int *right) {
    int temporary = *left;
    *left = *right;
    *right = temporary;
}

int partition(int *values, int low, int high) {
    int pivot = values[high];
    int boundary = low;
    for (int scan = low; scan < high; ++scan) {
        if (values[scan] < pivot) {
            swap(&values[boundary++], &values[scan]);
        }
    }
    swap(&values[boundary], &values[high]);
    return boundary;
}

void quick_sort(int *values, int low, int high) {
    if (low >= high) return;
    int pivot = partition(values, low, high);
    quick_sort(values, low, pivot - 1);
    quick_sort(values, pivot + 1, high);
}

int main(void) {
    int values[] = {9, 4, 7, 3, 10, 5};
    quick_sort(values, 0, 5);
    for (int index = 0; index < 6; ++index) {
        printf("%d ", values[index]);
    }
}
Output previsto
3 4 5 7 9 10
C++
Esegui →
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>

template<class Iterator>
void quick_sort(Iterator first, Iterator last) {
    if (last - first < 2) return;
    auto pivot = *(last - 1);
    auto middle = std::partition(first, last - 1,
        [pivot](int value) { return value < pivot; });
    std::iter_swap(middle, last - 1);
    quick_sort(first, middle);
    quick_sort(middle + 1, last);
}

int main() {
    std::vector values{9, 4, 7, 3, 10, 5};
    quick_sort(values.begin(), values.end());
    for (int value : values) {
        std::cout << value << ' ';
    }
}
Output previsto
3 4 5 7 9 10

Confronto tra C e C++

Media O(n log n), pivot sfavorevoli O(n²). C++ esprime la partizione con std::partition.

C

Loop, puntatori, dimensioni e buffer sono espliciti.

C++

Iteratori e algoritmi separano operazione e storage.

Esercizi pratici

Esegui entrambe le versioni e modificale per osservare le diverse garanzie.

  • Traccia ogni confronto.
  • Testa duplicati e valori estremi.
  • Confronta con la standard library.