-
Notifications
You must be signed in to change notification settings - Fork 1
/
antiqsort.c
107 lines (85 loc) · 1.96 KB
/
antiqsort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
/***********************
* McIlroy's antiqsort *
***********************/
int frozen = 1;
int gas;
int *data;
int antiqsort_cmp(const void *ap, const void *bp) {
int a, b;
static int candidate = 0;
a = *(int *)ap;
b = *(int *)bp;
if (data[a] == gas && data[b] == gas)
if (a == candidate)
data[a] = frozen++;
else
data[b] = frozen++;
if (data[a] == gas) {
candidate = a;
return 1;
}
if (data[b] == gas) {
candidate = b;
return -1;
}
return data[a] - data[b];
}
int *antiqsort(int nmemb) {
int *refs;
int i;
data = malloc(nmemb * sizeof(int));
refs = malloc(nmemb * sizeof(int));
gas = nmemb;
for (i=0; i<nmemb; i++) {
refs[i] = i;
data[i] = gas;
}
qsort(refs, nmemb, sizeof(int), antiqsort_cmp);
free(refs);
return data;
}
/**********************************
* Comparison counting comparator *
**********************************/
int count;
int cmp_int(const void *a, const void *b) {
count++;
return *(int *)a - *(int *)b;
}
/****************
* int main() ? *
****************/
int main(int argc, char *argv[]) {
int nmemb, *worst, i;
/* arguments */
if (argc != 2) {
fprintf(stderr, "Usage: %s <nmemb>\n", argv[0]);
return 1;
}
if (sscanf(argv[1], "%d", &nmemb) != 1) {
fprintf(stderr, "Fail: '%s' is not a number\n", argv[1]);
fprintf(stderr, "Usage: %s <nmemb>\n", argv[0]);
return 1;
}
/* generate a McIlroy killer adversary */
worst = antiqsort(nmemb);
#ifdef DUMPDIST
for (i=0; i<nmemb; i++)
printf("%d\n", worst[i]);
return 0;
#endif
/* qsort() the killer adversary and count comparisons */
printf("%d ", nmemb);
qsort(worst, nmemb, sizeof(int), cmp_int);
printf("%d ", count);
/* qsort() a random distribution for comparison */
for (i=0; i<nmemb; i++)
worst[i] = rand();
count = 0;
qsort(worst, nmemb, sizeof(int), cmp_int);
printf("%d\n", count);
return 0;
}