Select Git revision
loesung-2-f1.c
qsort-2.c 1.50 KiB
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int comparisons = 0;
void display (char **name, char *pivot, int left, int right)
{
printf ("\e[H\e[J");
for (int i = 0; name[i]; i++)
{
printf ("%s", name[i]);
if (name[i] == pivot)
printf (" <==");
else if (i == left || i == right)
printf (" <--");
printf ("\n");
}
printf ("%d\n", comparisons);
}
int compare (char **name, char *pivot, int left, int right)
{
int result = strcmp (name[left], pivot);
comparisons++;
display (name, pivot, left, right);
usleep (200000);
return result;
}
void quicksort (char **name, int left, int right)
{
int p = (left + right) / 2;
char *pivot = name[p];
int l = left;
int r = right;
while (l < r)
{
while (l < r && compare (name, pivot, l, r - 1) < 0)
l++;
while (l < r && compare (name, pivot, r - 1, l) > 0)
r--;
if (l < r)
{
char *temp = name[r - 1];
name[r - 1] = name[l];
name[l] = temp;
l++;
r--;
}
}
if (l < right)
quicksort (name, l, right);
}
void sort (char **name)
{
int r = 0;
while (name[r])
r++;
quicksort (name, 0, r);
}
int main (void)
{
char *name[] = { "Otto", "Lisa", "Anna", "Heinrich", "Siegfried", "Peter",
"Dieter", "Hugo", "Berta", "Maria", "Fritz", "Box", "Hans",
"Thomas", "Ulrich", "Zacharias", NULL };
sort (name);
display (name, NULL, -1, -1);
return 0;
}