diff --git a/10_sortierung/sortierung.c b/10_sortierung/sortierung.c index d33597c..866f6bf 100644 --- a/10_sortierung/sortierung.c +++ b/10_sortierung/sortierung.c @@ -1,4 +1,5 @@ #include "sortierung.h" +#include static void tausche(int *zahl1, int *zahl2) { @@ -26,7 +27,54 @@ void quickSort(int array[], int anzahl) } +static void mische(int links[], int rechts[], int anzahlLinks, int anzahlRechts) +{ + // Achtung: VLAs! Normalerweise verboten! + int hilfeLinks[anzahlLinks]; + int hilfeRechts[anzahlRechts]; + int idxLinks = 0; + int idxRechts = 0; + int *erg = links; + + memcpy(hilfeLinks, links, anzahlLinks * sizeof(int)); + memcpy(hilfeRechts, rechts, anzahlRechts * sizeof(int)); + + while(idxLinks < anzahlLinks && idxRechts < anzahlRechts) + { + if(hilfeLinks[idxLinks] <= hilfeRechts[idxRechts]) + { + *erg = hilfeLinks[idxLinks]; + idxLinks++; + } + else + { + *erg = hilfeRechts[idxRechts]; + idxRechts++; + } + erg++; + } + + for(; idxLinks < anzahlLinks; idxLinks++) + { + *erg = hilfeLinks[idxLinks]; + erg++; + } + + for(; idxRechts < anzahlRechts; idxRechts++) + { + *erg = hilfeRechts[idxRechts]; + erg++; + } + +} + void mergeSort(int array[], int anzahl) { - + if(anzahl > 1) + { + unsigned int mitte = anzahl / 2; + mergeSort(array, mitte); + mergeSort(array+mitte, anzahl - mitte); + mische(array, array+mitte, mitte, anzahl - mitte); + } } \ No newline at end of file diff --git a/10_sortierung/sortierungsvergleich.c b/10_sortierung/sortierungsvergleich.c index d43bf17..f551a0b 100644 --- a/10_sortierung/sortierungsvergleich.c +++ b/10_sortierung/sortierungsvergleich.c @@ -34,6 +34,10 @@ void gibArrayAus(int array[], int anzahl) printf("\n"); } +int vergleiche(const void *arg1, const void *arg2) +{ + return *(const int *)arg1 - *(const int *)arg2; +} int main() { @@ -46,8 +50,10 @@ int main() gibArrayAus(zufallszahlen, ANZAHL); starteUhr(); - selectionSort(zufallszahlen, ANZAHL); - //mergeSort(zufallszahlen, ANZAHL); + //selectionSort(zufallszahlen, ANZAHL); + mergeSort(zufallszahlen, ANZAHL); + //quickSort(zufallszahlen, ANZAHL); + //qsort(zufallszahlen, ANZAHL, sizeof(zufallszahlen[0]), vergleiche); printf("Zahlen sortiert nach %lf Sekunden.\n", messeZeitInSek());