xref: /freebsd/lib/libc/stdlib/qsort.c (revision dc36d6f9)
158f0484fSRodney W. Grimes /*-
28a16b7a1SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
38a16b7a1SPedro F. Giffuni  *
458f0484fSRodney W. Grimes  * Copyright (c) 1992, 1993
558f0484fSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
658f0484fSRodney W. Grimes  *
758f0484fSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
858f0484fSRodney W. Grimes  * modification, are permitted provided that the following conditions
958f0484fSRodney W. Grimes  * are met:
1058f0484fSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
1158f0484fSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
1258f0484fSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
1358f0484fSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
1458f0484fSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
15580b4d18SEd Maste  * 3. Neither the name of the University nor the names of its contributors
1658f0484fSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
1758f0484fSRodney W. Grimes  *    without specific prior written permission.
1858f0484fSRodney W. Grimes  *
1958f0484fSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2058f0484fSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2158f0484fSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2258f0484fSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2358f0484fSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2458f0484fSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2558f0484fSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2658f0484fSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2758f0484fSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2858f0484fSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2958f0484fSRodney W. Grimes  * SUCH DAMAGE.
3058f0484fSRodney W. Grimes  */
3158f0484fSRodney W. Grimes 
320d2fabfcSEdward Tomasz Napierala #include <errno.h>
330d2fabfcSEdward Tomasz Napierala #include <stdint.h>
3458f0484fSRodney W. Grimes #include <stdlib.h>
350d2fabfcSEdward Tomasz Napierala #include <string.h>
360d2fabfcSEdward Tomasz Napierala #include "libc_private.h"
3758f0484fSRodney W. Grimes 
380d2fabfcSEdward Tomasz Napierala #if defined(I_AM_QSORT_R)
39af3c7888SEd Schouten typedef int		 cmp_t(const void *, const void *, void *);
40af3c7888SEd Schouten #elif defined(I_AM_QSORT_R_COMPAT)
41eca67d51SGarrett Wollman typedef int		 cmp_t(void *, const void *, const void *);
420d2fabfcSEdward Tomasz Napierala #elif defined(I_AM_QSORT_S)
430d2fabfcSEdward Tomasz Napierala typedef int		 cmp_t(const void *, const void *, void *);
44eca67d51SGarrett Wollman #else
45c05ac53bSDavid E. O'Brien typedef int		 cmp_t(const void *, const void *);
46eca67d51SGarrett Wollman #endif
47eca67d51SGarrett Wollman static inline char	*med3(char *, char *, char *, cmp_t *, void *);
4858f0484fSRodney W. Grimes 
492eaea119SPedro F. Giffuni #define	MIN(a, b)	((a) < (b) ? a : b)
5058f0484fSRodney W. Grimes 
5158f0484fSRodney W. Grimes /*
5258f0484fSRodney W. Grimes  * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
5358f0484fSRodney W. Grimes  */
5458f0484fSRodney W. Grimes 
5558f0484fSRodney W. Grimes static inline void
swapfunc(char * a,char * b,size_t es)5666092616SKonstantin Belousov swapfunc(char *a, char *b, size_t es)
5758f0484fSRodney W. Grimes {
5866092616SKonstantin Belousov 	char t;
5966092616SKonstantin Belousov 
6066092616SKonstantin Belousov 	do {
6166092616SKonstantin Belousov 		t = *a;
6266092616SKonstantin Belousov 		*a++ = *b;
6366092616SKonstantin Belousov 		*b++ = t;
6466092616SKonstantin Belousov 	} while (--es > 0);
6558f0484fSRodney W. Grimes }
6658f0484fSRodney W. Grimes 
679382fabfSPedro F. Giffuni #define	vecswap(a, b, n)				\
6866092616SKonstantin Belousov 	if ((n) > 0) swapfunc(a, b, n)
6958f0484fSRodney W. Grimes 
700d2fabfcSEdward Tomasz Napierala #if defined(I_AM_QSORT_R)
71af3c7888SEd Schouten #define	CMP(t, x, y) (cmp((x), (y), (t)))
72af3c7888SEd Schouten #elif defined(I_AM_QSORT_R_COMPAT)
73eca67d51SGarrett Wollman #define	CMP(t, x, y) (cmp((t), (x), (y)))
740d2fabfcSEdward Tomasz Napierala #elif defined(I_AM_QSORT_S)
750d2fabfcSEdward Tomasz Napierala #define	CMP(t, x, y) (cmp((x), (y), (t)))
76eca67d51SGarrett Wollman #else
77eca67d51SGarrett Wollman #define	CMP(t, x, y) (cmp((x), (y)))
78eca67d51SGarrett Wollman #endif
79eca67d51SGarrett Wollman 
8058f0484fSRodney W. Grimes static inline char *
med3(char * a,char * b,char * c,cmp_t * cmp,void * thunk __unused)81eca67d51SGarrett Wollman med3(char *a, char *b, char *c, cmp_t *cmp, void *thunk
82af3c7888SEd Schouten #if !defined(I_AM_QSORT_R) && !defined(I_AM_QSORT_R_COMPAT) && !defined(I_AM_QSORT_S)
83eca67d51SGarrett Wollman __unused
84eca67d51SGarrett Wollman #endif
85eca67d51SGarrett Wollman )
8658f0484fSRodney W. Grimes {
87eca67d51SGarrett Wollman 	return CMP(thunk, a, b) < 0 ?
88eca67d51SGarrett Wollman 	       (CMP(thunk, b, c) < 0 ? b : (CMP(thunk, a, c) < 0 ? c : a ))
89eca67d51SGarrett Wollman 	      :(CMP(thunk, b, c) > 0 ? b : (CMP(thunk, a, c) < 0 ? a : c ));
9058f0484fSRodney W. Grimes }
9158f0484fSRodney W. Grimes 
92cbcfe28fSAlex Richardson /*
93cbcfe28fSAlex Richardson  * The actual qsort() implementation is static to avoid preemptible calls when
94cbcfe28fSAlex Richardson  * recursing. Also give them different names for improved debugging.
95cbcfe28fSAlex Richardson  */
960d2fabfcSEdward Tomasz Napierala #if defined(I_AM_QSORT_R)
97cbcfe28fSAlex Richardson #define local_qsort local_qsort_r
98af3c7888SEd Schouten #elif defined(I_AM_QSORT_R_COMPAT)
99af3c7888SEd Schouten #define local_qsort local_qsort_r_compat
1000d2fabfcSEdward Tomasz Napierala #elif defined(I_AM_QSORT_S)
101cbcfe28fSAlex Richardson #define local_qsort local_qsort_s
102eca67d51SGarrett Wollman #endif
103cbcfe28fSAlex Richardson static void
local_qsort(void * a,size_t n,size_t es,cmp_t * cmp,void * thunk)104cbcfe28fSAlex Richardson local_qsort(void *a, size_t n, size_t es, cmp_t *cmp, void *thunk)
10558f0484fSRodney W. Grimes {
10658f0484fSRodney W. Grimes 	char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
107ca1578f0SXin LI 	size_t d1, d2;
108ac48ad2eSDavid Schultz 	int cmp_result;
10966092616SKonstantin Belousov 	int swap_cnt;
11058f0484fSRodney W. Grimes 
111ecb2ce3aSHans Petter Selasky 	/* if there are less than 2 elements, then sorting is not needed */
112ecb2ce3aSHans Petter Selasky 	if (__predict_false(n < 2))
113d106f982SStefan Eßer 		return;
11466092616SKonstantin Belousov loop:
11558f0484fSRodney W. Grimes 	swap_cnt = 0;
11658f0484fSRodney W. Grimes 	if (n < 7) {
11709a8dfa2SBruce Evans 		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
118eca67d51SGarrett Wollman 			for (pl = pm;
119eca67d51SGarrett Wollman 			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
12058f0484fSRodney W. Grimes 			     pl -= es)
12166092616SKonstantin Belousov 				swapfunc(pl, pl - es, es);
12258f0484fSRodney W. Grimes 		return;
12358f0484fSRodney W. Grimes 	}
12409a8dfa2SBruce Evans 	pm = (char *)a + (n / 2) * es;
12558f0484fSRodney W. Grimes 	if (n > 7) {
12658f0484fSRodney W. Grimes 		pl = a;
12709a8dfa2SBruce Evans 		pn = (char *)a + (n - 1) * es;
12858f0484fSRodney W. Grimes 		if (n > 40) {
129ca1578f0SXin LI 			size_t d = (n / 8) * es;
130ca1578f0SXin LI 
131eca67d51SGarrett Wollman 			pl = med3(pl, pl + d, pl + 2 * d, cmp, thunk);
132eca67d51SGarrett Wollman 			pm = med3(pm - d, pm, pm + d, cmp, thunk);
133eca67d51SGarrett Wollman 			pn = med3(pn - 2 * d, pn - d, pn, cmp, thunk);
13458f0484fSRodney W. Grimes 		}
135eca67d51SGarrett Wollman 		pm = med3(pl, pm, pn, cmp, thunk);
13658f0484fSRodney W. Grimes 	}
13766092616SKonstantin Belousov 	swapfunc(a, pm, es);
13809a8dfa2SBruce Evans 	pa = pb = (char *)a + es;
13958f0484fSRodney W. Grimes 
14009a8dfa2SBruce Evans 	pc = pd = (char *)a + (n - 1) * es;
14158f0484fSRodney W. Grimes 	for (;;) {
142ac48ad2eSDavid Schultz 		while (pb <= pc && (cmp_result = CMP(thunk, pb, a)) <= 0) {
143ac48ad2eSDavid Schultz 			if (cmp_result == 0) {
14458f0484fSRodney W. Grimes 				swap_cnt = 1;
14566092616SKonstantin Belousov 				swapfunc(pa, pb, es);
14658f0484fSRodney W. Grimes 				pa += es;
14758f0484fSRodney W. Grimes 			}
14858f0484fSRodney W. Grimes 			pb += es;
14958f0484fSRodney W. Grimes 		}
150ac48ad2eSDavid Schultz 		while (pb <= pc && (cmp_result = CMP(thunk, pc, a)) >= 0) {
151ac48ad2eSDavid Schultz 			if (cmp_result == 0) {
15258f0484fSRodney W. Grimes 				swap_cnt = 1;
15366092616SKonstantin Belousov 				swapfunc(pc, pd, es);
15458f0484fSRodney W. Grimes 				pd -= es;
15558f0484fSRodney W. Grimes 			}
15658f0484fSRodney W. Grimes 			pc -= es;
15758f0484fSRodney W. Grimes 		}
15858f0484fSRodney W. Grimes 		if (pb > pc)
15958f0484fSRodney W. Grimes 			break;
16066092616SKonstantin Belousov 		swapfunc(pb, pc, es);
16158f0484fSRodney W. Grimes 		swap_cnt = 1;
16258f0484fSRodney W. Grimes 		pb += es;
16358f0484fSRodney W. Grimes 		pc -= es;
16458f0484fSRodney W. Grimes 	}
16558f0484fSRodney W. Grimes 	if (swap_cnt == 0) {  /* Switch to insertion sort */
16609a8dfa2SBruce Evans 		for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
167eca67d51SGarrett Wollman 			for (pl = pm;
168eca67d51SGarrett Wollman 			     pl > (char *)a && CMP(thunk, pl - es, pl) > 0;
16958f0484fSRodney W. Grimes 			     pl -= es)
17066092616SKonstantin Belousov 				swapfunc(pl, pl - es, es);
17158f0484fSRodney W. Grimes 		return;
17258f0484fSRodney W. Grimes 	}
17358f0484fSRodney W. Grimes 
17409a8dfa2SBruce Evans 	pn = (char *)a + n * es;
175ca1578f0SXin LI 	d1 = MIN(pa - (char *)a, pb - pa);
176ca1578f0SXin LI 	vecswap(a, pb - d1, d1);
1777f8f79a5SConrad Meyer 	/*
1787f8f79a5SConrad Meyer 	 * Cast es to preserve signedness of right-hand side of MIN()
1797f8f79a5SConrad Meyer 	 * expression, to avoid sign ambiguity in the implied comparison.  es
1807f8f79a5SConrad Meyer 	 * is safely within [0, SSIZE_MAX].
1817f8f79a5SConrad Meyer 	 */
1827f8f79a5SConrad Meyer 	d1 = MIN(pd - pc, pn - pd - (ssize_t)es);
183ca1578f0SXin LI 	vecswap(pb, pn - d1, d1);
184ca1578f0SXin LI 
185ca1578f0SXin LI 	d1 = pb - pa;
186ca1578f0SXin LI 	d2 = pd - pc;
187ca1578f0SXin LI 	if (d1 <= d2) {
188ca1578f0SXin LI 		/* Recurse on left partition, then iterate on right partition */
189ca1578f0SXin LI 		if (d1 > es) {
190cbcfe28fSAlex Richardson 			local_qsort(a, d1 / es, es, cmp, thunk);
191ca1578f0SXin LI 		}
192ca1578f0SXin LI 		if (d2 > es) {
19358f0484fSRodney W. Grimes 			/* Iterate rather than recurse to save stack space */
194ca1578f0SXin LI 			/* qsort(pn - d2, d2 / es, es, cmp); */
195ca1578f0SXin LI 			a = pn - d2;
196ca1578f0SXin LI 			n = d2 / es;
19758f0484fSRodney W. Grimes 			goto loop;
19858f0484fSRodney W. Grimes 		}
199ca1578f0SXin LI 	} else {
200ca1578f0SXin LI 		/* Recurse on right partition, then iterate on left partition */
201ca1578f0SXin LI 		if (d2 > es) {
202cbcfe28fSAlex Richardson 			local_qsort(pn - d2, d2 / es, es, cmp, thunk);
203ca1578f0SXin LI 		}
204ca1578f0SXin LI 		if (d1 > es) {
205ca1578f0SXin LI 			/* Iterate rather than recurse to save stack space */
206ca1578f0SXin LI 			/* qsort(a, d1 / es, es, cmp); */
207ca1578f0SXin LI 			n = d1 / es;
208ca1578f0SXin LI 			goto loop;
209ca1578f0SXin LI 		}
210ca1578f0SXin LI 	}
21158f0484fSRodney W. Grimes }
212cbcfe28fSAlex Richardson 
213cbcfe28fSAlex Richardson #if defined(I_AM_QSORT_R)
214cbcfe28fSAlex Richardson void
215af3c7888SEd Schouten (qsort_r)(void *a, size_t n, size_t es, cmp_t *cmp, void *thunk)
216cbcfe28fSAlex Richardson {
217cbcfe28fSAlex Richardson 	local_qsort_r(a, n, es, cmp, thunk);
218cbcfe28fSAlex Richardson }
219af3c7888SEd Schouten #elif defined(I_AM_QSORT_R_COMPAT)
220af3c7888SEd Schouten void
__qsort_r_compat(void * a,size_t n,size_t es,void * thunk,cmp_t * cmp)221af3c7888SEd Schouten __qsort_r_compat(void *a, size_t n, size_t es, void *thunk, cmp_t *cmp)
222af3c7888SEd Schouten {
223af3c7888SEd Schouten 	local_qsort_r_compat(a, n, es, cmp, thunk);
224af3c7888SEd Schouten }
225cbcfe28fSAlex Richardson #elif defined(I_AM_QSORT_S)
226cbcfe28fSAlex Richardson errno_t
qsort_s(void * a,rsize_t n,rsize_t es,cmp_t * cmp,void * thunk)227cbcfe28fSAlex Richardson qsort_s(void *a, rsize_t n, rsize_t es, cmp_t *cmp, void *thunk)
228cbcfe28fSAlex Richardson {
229cbcfe28fSAlex Richardson 	if (n > RSIZE_MAX) {
230cbcfe28fSAlex Richardson 		__throw_constraint_handler_s("qsort_s : n > RSIZE_MAX", EINVAL);
231cbcfe28fSAlex Richardson 		return (EINVAL);
232cbcfe28fSAlex Richardson 	} else if (es > RSIZE_MAX) {
233cbcfe28fSAlex Richardson 		__throw_constraint_handler_s("qsort_s : es > RSIZE_MAX",
234cbcfe28fSAlex Richardson 		    EINVAL);
235cbcfe28fSAlex Richardson 		return (EINVAL);
236cbcfe28fSAlex Richardson 	} else if (n != 0) {
237cbcfe28fSAlex Richardson 		if (a == NULL) {
238cbcfe28fSAlex Richardson 			__throw_constraint_handler_s("qsort_s : a == NULL",
239cbcfe28fSAlex Richardson 			    EINVAL);
240cbcfe28fSAlex Richardson 			return (EINVAL);
241cbcfe28fSAlex Richardson 		} else if (cmp == NULL) {
242cbcfe28fSAlex Richardson 			__throw_constraint_handler_s("qsort_s : cmp == NULL",
243cbcfe28fSAlex Richardson 			    EINVAL);
244cbcfe28fSAlex Richardson 			return (EINVAL);
24527bb0d33SHans Petter Selasky 		} else if (es <= 0) {
24627bb0d33SHans Petter Selasky 			__throw_constraint_handler_s("qsort_s : es <= 0",
24727bb0d33SHans Petter Selasky 			    EINVAL);
24827bb0d33SHans Petter Selasky 			return (EINVAL);
249cbcfe28fSAlex Richardson 		}
250cbcfe28fSAlex Richardson 	}
251cbcfe28fSAlex Richardson 
252cbcfe28fSAlex Richardson 	local_qsort_s(a, n, es, cmp, thunk);
253cbcfe28fSAlex Richardson 	return (0);
254cbcfe28fSAlex Richardson }
255cbcfe28fSAlex Richardson #else
256cbcfe28fSAlex Richardson void
qsort(void * a,size_t n,size_t es,cmp_t * cmp)257cbcfe28fSAlex Richardson qsort(void *a, size_t n, size_t es, cmp_t *cmp)
258cbcfe28fSAlex Richardson {
259cbcfe28fSAlex Richardson 	local_qsort(a, n, es, cmp, NULL);
260cbcfe28fSAlex Richardson }
261cbcfe28fSAlex Richardson #endif
262