Commented
This commit is contained in:
parent
ef0c63656d
commit
20921665f0
|
|
@ -1,40 +1,51 @@
|
|||
void insertionSortBase(int array[], int array_size, bool asc) {
|
||||
int i = 0;
|
||||
while(i<array_size){
|
||||
|
||||
// Dieser Loop wird "array_size" (=n) mal ausgeführt.
|
||||
while (i < array_size) {
|
||||
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];
|
||||
array[j] = array[j-1];
|
||||
array[j-1] = currentValue;
|
||||
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){
|
||||
while (i < array_size) {
|
||||
int x = array[i];
|
||||
int j = i-1;
|
||||
while(j >= 0 && array[j] > x){
|
||||
array[j+1] = array[j];
|
||||
int j = i - 1;
|
||||
while (j >= 0 && array[j] > x) {
|
||||
array[j + 1] = array[j];
|
||||
j--;
|
||||
}
|
||||
array[j+1] = x;
|
||||
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) {
|
||||
if(array_size > 0) {
|
||||
insertionSortRecursive(array, array_size-1, true);
|
||||
int x = array[array_size-1];
|
||||
int j = array_size-2;
|
||||
while( j >= 0 && array[j] > x){
|
||||
array[j+1] = array[j];
|
||||
// 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;
|
||||
array[j + 1] = x;
|
||||
}
|
||||
}
|
||||
// Insgesamt: O(n*n) = O(n^2)
|
||||
Loading…
Reference in New Issue