Commented
This commit is contained in:
parent
ef0c63656d
commit
20921665f0
|
|
@ -1,7 +1,10 @@
|
|||
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];
|
||||
|
|
@ -11,6 +14,7 @@ void insertionSortBase(int array[], int array_size, bool asc) {
|
|||
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;
|
||||
|
|
@ -25,12 +29,18 @@ void insertionSortOptimized(int array[], int array_size, bool asc) {
|
|||
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--;
|
||||
|
|
@ -38,3 +48,4 @@ void insertionSortRecursive(int array[], int array_size, bool asc) {
|
|||
array[j + 1] = x;
|
||||
}
|
||||
}
|
||||
// Insgesamt: O(n*n) = O(n^2)
|
||||
Loading…
Reference in New Issue