Sobes.tech
Middle — Senior

Wie ist die Komplexität der Sortieralgorithmen?

sobes.tech KI

Antwort von AI

Die Komplexität von Sortieralgorithmen wird in der Regel nach Zeit und Speicher bewertet.

  • Bubble Sort: Zeit — O(n²), Speicher — O(1). Einfach, aber ineffizient für große Datenmengen.
  • Insertion Sort: Zeit — O(n²) im schlimmsten Fall, O(n) im besten (fast sortiertes Array), Speicher — O(1).
  • Merge Sort: Zeit — O(n log n) in jedem Fall, Speicher — O(n) aufgrund eines zusätzlichen Arrays.
  • Quick Sort: Durchschnittliche Zeit — O(n log n), schlimmster Fall — O(n²), Speicher — O(log n) durch Rekursion.
  • Heap Sort: Zeit — O(n log n), Speicher — O(1).

Beispiel für Quick Sort in Java:

public static void quickSort(int[] arr, int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

private static int partition(int[] arr, int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    return i + 1;
}