Quicksort

Quicksort

Arbeitsweise

  1. Pivot-Auswahl: Wähle ein Element als Pivot (z. B. low).
  2. Partitionierung: Ordne das Array so um, dass alle Elemente, die kleiner oder gleich dem Pivot sind, links und alle, die größer sind, rechts angeordnet werden. Am Ende der Partitionierung steht der Pivot an seiner endgültigen Position.
  3. Rekursion: Wende diesen Vorgang rekursiv auf die beiden Teillisten (links und rechts vom Pivot) an, bis die Listen 0 oder 1 Element enthalten.

!introprog-v10-sortieren-teil2, p.7

Komplexität

Varianten

Quick Sort mit Listen

Beispiele

Beispiel 1 (aus Vorlesung)

Beispiel 2 (Wikipedia)

Stabilität

Quicksort ist nur dann stabil, wenn alle Elemente mit dem gleichen Wert des gewählten Pivots, die vor bzw. nach dem Pivot kommen, auch entsprechend in die linke bzw. rechte Liste gehen.

Pseudocode

QuickSort (list to sort)1.// Abbruchbedingung2.if (tosort.first = tosort.last)3.return4.else5.list left, right6.pivot  Partition(tosort, left, right)7.// Rekursion8.QuickSort(left)9.QuickSort(right)10.// Listen zusammenfügen11.if (left.first = NULL) // Test auf Gleichheit!12.tosort.first  pivot13.tosort.last  pivot14.else15.tosort.first  left.first16.left.last.next  pivot17.if (right.first = NULL) // Test auf Gleichheit!18.pivot.next  NULL19.tosort.last  pivot20.else21.pivot.next  right.first

Quick Sort in C

// C program to implement Quick Sort Algorithm
#include <stdio.h>

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int low, int high) {

    // Initialize pivot to be the first element
    int p = arr[low];
    int i = low;
    int j = high;

    while (i < j) {

        // Find the first element greater than
        // the pivot (from starting)
        while (arr[i] <= p && i <= high - 1) {
            i++;
        }

        // Find the first element smaller than
        // the pivot (from last)
        while (arr[j] > p && j >= low + 1) {
            j--;
        }
        if (i < j) {
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[low], &arr[j]);
    return j;
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {

        // call partition function to find Partition Index
        int pi = partition(arr, low, high);

        // Recursively call quickSort() for left and right
        // half based on Partition Index
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
  
    int arr[] = { 4, 2, 5, 3, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);

    // calling quickSort() to sort the given array
    quickSort(arr, 0, n - 1);

    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}