xref: /freebsd/lib/libc/stdlib/qsort.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if defined(LIBC_SCCS) && !defined(lint)
33 static char sccsid[] = "@(#)qsort.c	8.1 (Berkeley) 6/4/93";
34 #endif /* LIBC_SCCS and not lint */
35 #include <sys/cdefs.h>
36 #include <errno.h>
37 #include <stdint.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include "libc_private.h"
41 
42 #if defined(I_AM_QSORT_R)
43 typedef int		 cmp_t(const void *, const void *, void *);
44 #elif defined(I_AM_QSORT_R_COMPAT)
45 typedef int		 cmp_t(void *, const void *, const void *);
46 #elif defined(I_AM_QSORT_S)
47 typedef int		 cmp_t(const void *, const void *, void *);
48 #else
49 typedef int		 cmp_t(const void *, const void *);
50 #endif
51 static inline char	*med3(char *, char *, char *, cmp_t *, void *);
52 
53 #define	MIN(a, b)	((a) < (b) ? a : b)
54 
55 /*
56  * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
57  */
58 
59 static inline void
60 swapfunc(char *a, char *b, size_t es)
61 {
62 	char t;
63 
64 	do {
65 		t = *a;
66 		*a++ = *b;
67 		*b++ = t;
68 	} while (--es > 0);
69 }
70 
71 #define	vecswap(a, b, n)				\
72 	if ((n) > 0) swapfunc(a, b, n)
73 
74 #if defined(I_AM_QSORT_R)
75 #define	CMP(t, x, y) (cmp((x), (y), (t)))
76 #elif defined(I_AM_QSORT_R_COMPAT)
77 #define	CMP(t, x, y) (cmp((t), (x), (y)))
78 #elif defined(I_AM_QSORT_S)
79 #define	CMP(t, x, y) (cmp((x), (y), (t)))
80 #else
81 #define	CMP(t, x, y) (cmp((x), (y)))
82 #endif
83 
84 static inline char *
85 med3(char *a, char *b, char *c, cmp_t *cmp, void *thunk
86 #if !defined(I_AM_QSORT_R) && !defined(I_AM_QSORT_R_COMPAT) && !defined(I_AM_QSORT_S)
87 __unused
88 #endif
89 )
90 {
91 	return CMP(thunk, a, b) < 0 ?
92 	       (CMP(thunk, b, c) < 0 ? b : (CMP(thunk, a, c) < 0 ? c : a ))
93 	      :(CMP(thunk, b, c) > 0 ? b : (CMP(thunk, a, c) < 0 ? a : c ));
94 }
95 
96 /*
97  * The actual qsort() implementation is static to avoid preemptible calls when
98  * recursing. Also give them different names for improved debugging.
99  */
100 #if defined(I_AM_QSORT_R)
101 #define local_qsort local_qsort_r
102 #elif defined(I_AM_QSORT_R_COMPAT)
103 #define local_qsort local_qsort_r_compat
104 #elif defined(I_AM_QSORT_S)
105 #define local_qsort local_qsort_s
106 #endif
107 static void
108 local_qsort(void *a, size_t n, size_t es, cmp_t *cmp, void *thunk)
109 {
110 	char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
111 	size_t d1, d2;
112 	int cmp_result;
113 	int swap_cnt;
114 
115 	/* if there are less than 2 elements, then sorting is not needed */
116 	if (__predict_false(n < 2))
117 		return;
118 loop:
119 	swap_cnt = 0;
120 	if (n < 7) {
121 		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
122 			for (pl = pm;
123 			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
124 			     pl -= es)
125 				swapfunc(pl, pl - es, es);
126 		return;
127 	}
128 	pm = (char *)a + (n / 2) * es;
129 	if (n > 7) {
130 		pl = a;
131 		pn = (char *)a + (n - 1) * es;
132 		if (n > 40) {
133 			size_t d = (n / 8) * es;
134 
135 			pl = med3(pl, pl + d, pl + 2 * d, cmp, thunk);
136 			pm = med3(pm - d, pm, pm + d, cmp, thunk);
137 			pn = med3(pn - 2 * d, pn - d, pn, cmp, thunk);
138 		}
139 		pm = med3(pl, pm, pn, cmp, thunk);
140 	}
141 	swapfunc(a, pm, es);
142 	pa = pb = (char *)a + es;
143 
144 	pc = pd = (char *)a + (n - 1) * es;
145 	for (;;) {
146 		while (pb <= pc && (cmp_result = CMP(thunk, pb, a)) <= 0) {
147 			if (cmp_result == 0) {
148 				swap_cnt = 1;
149 				swapfunc(pa, pb, es);
150 				pa += es;
151 			}
152 			pb += es;
153 		}
154 		while (pb <= pc && (cmp_result = CMP(thunk, pc, a)) >= 0) {
155 			if (cmp_result == 0) {
156 				swap_cnt = 1;
157 				swapfunc(pc, pd, es);
158 				pd -= es;
159 			}
160 			pc -= es;
161 		}
162 		if (pb > pc)
163 			break;
164 		swapfunc(pb, pc, es);
165 		swap_cnt = 1;
166 		pb += es;
167 		pc -= es;
168 	}
169 	if (swap_cnt == 0) {  /* Switch to insertion sort */
170 		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
171 			for (pl = pm;
172 			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
173 			     pl -= es)
174 				swapfunc(pl, pl - es, es);
175 		return;
176 	}
177 
178 	pn = (char *)a + n * es;
179 	d1 = MIN(pa - (char *)a, pb - pa);
180 	vecswap(a, pb - d1, d1);
181 	/*
182 	 * Cast es to preserve signedness of right-hand side of MIN()
183 	 * expression, to avoid sign ambiguity in the implied comparison.  es
184 	 * is safely within [0, SSIZE_MAX].
185 	 */
186 	d1 = MIN(pd - pc, pn - pd - (ssize_t)es);
187 	vecswap(pb, pn - d1, d1);
188 
189 	d1 = pb - pa;
190 	d2 = pd - pc;
191 	if (d1 <= d2) {
192 		/* Recurse on left partition, then iterate on right partition */
193 		if (d1 > es) {
194 			local_qsort(a, d1 / es, es, cmp, thunk);
195 		}
196 		if (d2 > es) {
197 			/* Iterate rather than recurse to save stack space */
198 			/* qsort(pn - d2, d2 / es, es, cmp); */
199 			a = pn - d2;
200 			n = d2 / es;
201 			goto loop;
202 		}
203 	} else {
204 		/* Recurse on right partition, then iterate on left partition */
205 		if (d2 > es) {
206 			local_qsort(pn - d2, d2 / es, es, cmp, thunk);
207 		}
208 		if (d1 > es) {
209 			/* Iterate rather than recurse to save stack space */
210 			/* qsort(a, d1 / es, es, cmp); */
211 			n = d1 / es;
212 			goto loop;
213 		}
214 	}
215 }
216 
217 #if defined(I_AM_QSORT_R)
218 void
219 (qsort_r)(void *a, size_t n, size_t es, cmp_t *cmp, void *thunk)
220 {
221 	local_qsort_r(a, n, es, cmp, thunk);
222 }
223 #elif defined(I_AM_QSORT_R_COMPAT)
224 void
225 __qsort_r_compat(void *a, size_t n, size_t es, void *thunk, cmp_t *cmp)
226 {
227 	local_qsort_r_compat(a, n, es, cmp, thunk);
228 }
229 #elif defined(I_AM_QSORT_S)
230 errno_t
231 qsort_s(void *a, rsize_t n, rsize_t es, cmp_t *cmp, void *thunk)
232 {
233 	if (n > RSIZE_MAX) {
234 		__throw_constraint_handler_s("qsort_s : n > RSIZE_MAX", EINVAL);
235 		return (EINVAL);
236 	} else if (es > RSIZE_MAX) {
237 		__throw_constraint_handler_s("qsort_s : es > RSIZE_MAX",
238 		    EINVAL);
239 		return (EINVAL);
240 	} else if (n != 0) {
241 		if (a == NULL) {
242 			__throw_constraint_handler_s("qsort_s : a == NULL",
243 			    EINVAL);
244 			return (EINVAL);
245 		} else if (cmp == NULL) {
246 			__throw_constraint_handler_s("qsort_s : cmp == NULL",
247 			    EINVAL);
248 			return (EINVAL);
249 		} else if (es <= 0) {
250 			__throw_constraint_handler_s("qsort_s : es <= 0",
251 			    EINVAL);
252 			return (EINVAL);
253 		}
254 	}
255 
256 	local_qsort_s(a, n, es, cmp, thunk);
257 	return (0);
258 }
259 #else
260 void
261 qsort(void *a, size_t n, size_t es, cmp_t *cmp)
262 {
263 	local_qsort(a, n, es, cmp, NULL);
264 }
265 #endif
266