2 * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
3 * See the copyright notice in the ACK home directory, in the file "Copyright".
9 static void qsort1(char *, char *, size_t);
10 static int (*qcompar
)(const char *, const char *);
11 static void qexchange(char *, char *, size_t);
12 static void q3exchange(char *, char *, char *, size_t);
15 qsort(void *base
, size_t nel
, size_t width
,
16 int (*compar
)(const void *, const void *))
18 /* when nel is 0, the expression '(nel - 1) * width' is wrong */
20 qcompar
= (int (*)(const char *, const char *)) compar
;
21 qsort1(base
, (char *)base
+ (nel
- 1) * width
, width
);
25 qsort1(char *a1
, char *a2
, register size_t width
)
27 register char *left
, *right
;
28 register char *lefteq
, *righteq
;
35 lefteq
= righteq
= a1
+ width
* (((a2
-a1
)+width
)/(2*width
));
37 Pick an element in the middle of the array.
38 We will collect the equals around it.
39 "lefteq" and "righteq" indicate the left and right
40 bounds of the equals respectively.
41 Smaller elements end up left of it, larger elements end
45 while (left
< lefteq
&& (cmp
= (*qcompar
)(left
, lefteq
)) <= 0) {
47 /* leave it where it is */
51 /* equal, so exchange with the element to
52 the left of the "equal"-interval.
55 qexchange(left
, lefteq
, width
);
58 while (right
> righteq
) {
59 if ((cmp
= (*qcompar
)(right
, righteq
)) < 0) {
60 /* smaller, should go to left part
63 /* yes, we had a larger one at the
64 left, so we can just exchange
66 qexchange(left
, right
, width
);
71 /* no more room at the left part, so we
72 move the "equal-interval" one place to the
73 right, and the smaller element to the
75 This is best expressed as a three-way
79 q3exchange(left
, righteq
, right
, width
);
84 /* equal, so exchange with the element to
85 the right of the "equal-interval"
88 qexchange(right
, righteq
, width
);
90 else /* just leave it */ right
-= width
;
93 /* larger element to the left, but no more room,
94 so move the "equal-interval" one place to the
95 left, and the larger element to the right
99 q3exchange(right
, lefteq
, left
, width
);
104 /* now sort the "smaller" part */
105 qsort1(a1
, lefteq
- width
, width
);
106 /* and now the larger, saving a subroutine call
107 because of the for(;;)
109 a1
= righteq
+ width
;
115 qexchange(register char *p
, register char *q
,
128 q3exchange(register char *p
, register char *q
, register char *r
,