114 lines
2.5 KiB
C
114 lines
2.5 KiB
C
#include "sortierung.h"
|
|
#include <string.h>
|
|
|
|
static void tausche(int *zahl1, int *zahl2)
|
|
{
|
|
int tmp = *zahl1;
|
|
*zahl1 = *zahl2;
|
|
*zahl2 = tmp;
|
|
}
|
|
|
|
void selectionSort(int array[], int anzahl)
|
|
{
|
|
for(int i = 0; i < anzahl - 1; i++)
|
|
{
|
|
int minIdx = i;
|
|
for(int j = i + 1; j < anzahl; j++)
|
|
{
|
|
if(array[j] < array[minIdx])
|
|
minIdx = j;
|
|
}
|
|
tausche(&array[i], &array[minIdx]);
|
|
}
|
|
}
|
|
|
|
static int *sortiereUmPivot(int array[], unsigned int anzahl)
|
|
{
|
|
int *linksZgr = array;
|
|
int *rechtsZgr = array + anzahl - 1;
|
|
int *pivot = rechtsZgr;
|
|
|
|
rechtsZgr--;
|
|
|
|
while(linksZgr < rechtsZgr)
|
|
{
|
|
while(linksZgr < rechtsZgr && *linksZgr <= *pivot)
|
|
linksZgr++;
|
|
|
|
while(linksZgr < rechtsZgr && *rechtsZgr > *pivot)
|
|
rechtsZgr--;
|
|
|
|
if(*linksZgr > *rechtsZgr)
|
|
tausche(linksZgr, rechtsZgr);
|
|
}
|
|
|
|
if(*linksZgr <= *pivot)
|
|
linksZgr = pivot;
|
|
else
|
|
tausche(linksZgr, pivot);
|
|
|
|
return linksZgr;
|
|
}
|
|
|
|
void quickSort(int array[], int anzahl)
|
|
{
|
|
if(anzahl > 1)
|
|
{
|
|
int *pivot = sortiereUmPivot(array, anzahl);
|
|
unsigned int anzahlLinks = pivot - array;
|
|
quickSort(array, anzahlLinks);
|
|
quickSort(pivot, anzahl - anzahlLinks);
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
} |