Commented

This commit is contained in:
Samuel Oberhofer 2022-05-26 10:32:08 +02:00
parent ef0c63656d
commit 20921665f0
1 changed files with 44 additions and 33 deletions

View File

@ -1,40 +1,51 @@
void insertionSortBase(int array[], int array_size, bool asc) { void insertionSortBase(int array[], int array_size, bool asc) {
int i = 0; int i = 0;
while(i<array_size){
// Dieser Loop wird "array_size" (=n) mal ausgeführt.
while (i < array_size) {
int j = i; int j = i;
while(j > 0 && array[j-1] > array[j]){ // empirisch wird dieser Loop auch n mal ausgeführt
while (j > 0 && array[j - 1] > array[j]) {
int currentValue = array[j]; int currentValue = array[j];
array[j] = array[j-1]; array[j] = array[j - 1];
array[j-1] = currentValue; array[j - 1] = currentValue;
j--; j--;
} }
i++; i++;
} }
} }
// Zusammen ergibt das wieder eine worst case Komplexität von O(n^2)
void insertionSortOptimized(int array[], int array_size, bool asc) { void insertionSortOptimized(int array[], int array_size, bool asc) {
int i = 0; int i = 0;
while(i<array_size){ while (i < array_size) {
int x = array[i]; int x = array[i];
int j = i-1; int j = i - 1;
while(j >= 0 && array[j] > x){ while (j >= 0 && array[j] > x) {
array[j+1] = array[j]; array[j + 1] = array[j];
j--; j--;
} }
array[j+1] = x; array[j + 1] = x;
i++; 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) { void insertionSortRecursive(int array[], int array_size, bool asc) {
if(array_size > 0) { // in jedem Rekursionsschritt wird der Algorithmus mit array_size-1
insertionSortRecursive(array, array_size-1, true); // aufgerufen, und dann abgebrochen, wenn arraysize=0 ist. D.h. es werden
int x = array[array_size-1]; // insgesamt n Rekursionsschritte ausgeführt -> O(n)
int j = array_size-2; if (array_size > 0) {
while( j >= 0 && array[j] > x){ insertionSortRecursive(array, array_size - 1, true);
array[j+1] = array[j]; 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--; j--;
} }
array[j+1] = x; array[j + 1] = x;
} }
} }
// Insgesamt: O(n*n) = O(n^2)