Memory Management
* myprintf.c: Dynamic Memory allocation added
* prog_limit: fixed a segfault
committer: Markus Bröker <mbroeker@largo.homelinux.org>
/**
* Comparision of Sorting Algorithms
* Copyright (C) 2008 Markus Broeker
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifndef MAX
#define MAX 50000
#endif
unsigned long counter = 0;
unsigned long iters = 0;
int compare (int *a, int *b)
{
iters++;
if (*a > *b) {
counter++;
return 1;
}
return 0;
}
void swap (int *v, int i, int j)
{
int old = v[i];
v[i] = v[j];
v[j] = old;
}
void statistic (char *func)
{
printf ("%8s finished after %10lu swaps and %10lu Iterations.\n", func, counter, iters);
counter = iters = 0;
}
/**
* Laufzeitverhalten: n*(n-1) Durchläufe zum Sortieren von n Elementen...
*/
void lazysort (int *v, int n, int (*compare_func) (int *, int *))
{
int i, j;
for (i = 1; i < n; i++) {
for (j = 0; j < n; j++) {
if (compare_func (&v[j], &v[i])) {
swap (v, i, j);
}
}
}
statistic ("Lazy");
}
/**
* Laufzeitverhalten: (1/2)*n*(n-1) Durchläufe zum Sortieren von n Elementen...
*/
void bubblesort (int *v, int n, int (*compare) (int *, int *))
{
int i, j;
for (i = (n - 1); i >= 0; i--) {
for (j = 1; j <= i; j++) {
if (compare (&v[j - 1], &v[j])) {
swap (v, j - 1, j);
}
}
}
statistic ("Bubble");
}
int main (int argc, char **argv)
{
int a[MAX];
int b[MAX];
int c[MAX];
int i;
srand (time (NULL));
for (i = 0; i < MAX; i++) {
a[i] = (int)((float)MAX * rand () / (RAND_MAX + 1.0));
}
memcpy (b, a, sizeof (a));
memcpy (c, a, sizeof (a));
lazysort (a, MAX, &compare);
bubblesort (b, MAX, &compare);
qsort (c, MAX, sizeof (int), (void *)&compare);
statistic ("Quick");
printf ("PRESS <RETURN> to CONTINUE");
while (getchar () != 10);
printf ("%2c %2c %2c\n--------\n", 'L', 'B', 'Q');
for (i = 0; i < MAX; i++)
printf ("%2d %2d %2d\n", a[i], b[i], c[i]);
return EXIT_SUCCESS;
}