void insertionSortBase(int array[], int array_size, bool asc) { int i = 0; // Dieser Loop wird "array_size" (=n) mal ausgeführt. while (i < array_size) { int j = i; // empirisch wird dieser Loop auch n mal ausgeführt while (j > 0 && array[j - 1] > array[j]) { int currentValue = array[j]; array[j] = array[j - 1]; array[j - 1] = currentValue; j--; } i++; } } // Zusammen ergibt das wieder eine worst case Komplexität von O(n^2) void insertionSortOptimized(int array[], int array_size, bool asc) { int i = 0; while (i < array_size) { int x = array[i]; int j = i - 1; while (j >= 0 && array[j] > x) { array[j + 1] = array[j]; j--; } array[j + 1] = x; i++; } } // Hier werden wieder zwei Schleifen ineinander ausgeführt. Auch wenn die innere // Schleife effizienter ist bleibt die Komplexität O(n^2) void insertionSortRecursive(int array[], int array_size, bool asc) { // in jedem Rekursionsschritt wird der Algorithmus mit array_size-1 // aufgerufen, und dann abgebrochen, wenn arraysize=0 ist. D.h. es werden // insgesamt n Rekursionsschritte ausgeführt -> O(n) if (array_size > 0) { insertionSortRecursive(array, array_size - 1, true); int x = array[array_size - 1]; int j = array_size - 2; // Diese Schleife kann auch im worst case n mal ausgeführt werden -> O(n) while (j >= 0 && array[j] > x) { array[j + 1] = array[j]; j--; } array[j + 1] = x; } } // Insgesamt: O(n*n) = O(n^2)