mirror of
https://github.com/jart/cosmopolitan.git
synced 2025-03-02 23:18:44 +00:00
Import OpenBSD sorting algorithms
OpenBSD's qsort() function is more secure than the ones used by FreeBSD, NetBSD and MacOS. The best part is it goes faster too! This change also imports the OpenBSD mergesort() and heapsort()
This commit is contained in:
parent
dbf12c30b0
commit
d861d2787b
11 changed files with 912 additions and 215 deletions
|
@ -10,6 +10,8 @@ void *bsearch_r(const void *, const void *, size_t, size_t,
|
|||
int (*)(const void *, const void *, void *), void *)
|
||||
paramsnonnull((1, 2, 5)) dontthrow nosideeffect;
|
||||
void djbsort(int32_t *, size_t);
|
||||
void qsort3(void *, size_t, size_t, int (*)(const void *, const void *))
|
||||
paramsnonnull();
|
||||
void qsort(void *, size_t, size_t, int (*)(const void *, const void *))
|
||||
paramsnonnull();
|
||||
void qsort_r(void *, size_t, size_t,
|
||||
|
@ -18,6 +20,12 @@ void qsort_r(void *, size_t, size_t,
|
|||
void smoothsort(void *, size_t, size_t, int (*)(const void *, const void *));
|
||||
void smoothsort_r(void *, size_t, size_t,
|
||||
int (*)(const void *, const void *, void *), void *);
|
||||
int heapsort(void *, size_t, size_t, int (*)(const void *, const void *));
|
||||
int heapsort_r(void *, size_t, size_t,
|
||||
int (*)(const void *, const void *, void *), void *);
|
||||
int mergesort(void *, size_t, size_t, int (*)(const void *, const void *));
|
||||
int mergesort_r(void *, size_t, size_t,
|
||||
int (*)(const void *, const void *, void *), void *);
|
||||
int tarjan(int, const int (*)[2], int, int[], int[], int *)
|
||||
paramsnonnull((2, 4)) nocallback dontthrow;
|
||||
|
||||
|
|
198
libc/mem/heapsort.c
Normal file
198
libc/mem/heapsort.c
Normal file
|
@ -0,0 +1,198 @@
|
|||
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
|
||||
│vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│
|
||||
╞══════════════════════════════════════════════════════════════════════════════╡
|
||||
│ Copyright (c) 1991, 1993 │
|
||||
│ The Regents of the University of California. All rights reserved. │
|
||||
│ │
|
||||
│ Redistribution and use in source and binary forms, with or without │
|
||||
│ modification, are permitted provided that the following conditions │
|
||||
│ are met: │
|
||||
│ 1. Redistributions of source code must retain the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer. │
|
||||
│ 2. Redistributions in binary form must reproduce the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer in the │
|
||||
│ documentation and/or other materials provided with the distribution. │
|
||||
│ 3. Neither the name of the University nor the names of its contributors │
|
||||
│ may be used to endorse or promote products derived from this software │
|
||||
│ without specific prior written permission. │
|
||||
│ │
|
||||
│ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │
|
||||
│ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │
|
||||
│ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │
|
||||
│ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │
|
||||
│ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │
|
||||
│ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │
|
||||
│ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │
|
||||
│ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │
|
||||
│ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │
|
||||
│ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │
|
||||
│ SUCH DAMAGE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/mem/alg.h"
|
||||
#include "libc/mem/mem.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
// clang-format off
|
||||
|
||||
/*
|
||||
* Swap two areas of size number of bytes. Although qsort(3) permits random
|
||||
* blocks of memory to be sorted, sorting pointers is almost certainly the
|
||||
* common case (and, were it not, could easily be made so). Regardless, it
|
||||
* isn't worth optimizing; the SWAP's get sped up by the cache, and pointer
|
||||
* arithmetic gets lost in the time required for comparison function calls.
|
||||
*/
|
||||
#define SWAP(a, b, count, size, tmp) { \
|
||||
count = size; \
|
||||
do { \
|
||||
tmp = *a; \
|
||||
*a++ = *b; \
|
||||
*b++ = tmp; \
|
||||
} while (--count); \
|
||||
}
|
||||
|
||||
/* Copy one block of size size to another. */
|
||||
#define COPY(a, b, count, size, tmp1, tmp2) { \
|
||||
count = size; \
|
||||
tmp1 = a; \
|
||||
tmp2 = b; \
|
||||
do { \
|
||||
*tmp1++ = *tmp2++; \
|
||||
} while (--count); \
|
||||
}
|
||||
|
||||
/*
|
||||
* Build the list into a heap, where a heap is defined such that for
|
||||
* the records K1 ... KN, Kj/2 >= Kj for 1 <= j/2 <= j <= N.
|
||||
*
|
||||
* There are two cases. If j == nmemb, select largest of Ki and Kj. If
|
||||
* j < nmemb, select largest of Ki, Kj and Kj+1.
|
||||
*/
|
||||
#define CREATE(initval, nmemb, par_i, child_i, par, child, size, count, tmp) { \
|
||||
for (par_i = initval; (child_i = par_i * 2) <= nmemb; \
|
||||
par_i = child_i) { \
|
||||
child = base + child_i * size; \
|
||||
if (child_i < nmemb && compar(child, child + size, z) < 0) { \
|
||||
child += size; \
|
||||
++child_i; \
|
||||
} \
|
||||
par = base + par_i * size; \
|
||||
if (compar(child, par, z) <= 0) \
|
||||
break; \
|
||||
SWAP(par, child, count, size, tmp); \
|
||||
} \
|
||||
}
|
||||
|
||||
/*
|
||||
* Select the top of the heap and 'heapify'. Since by far the most expensive
|
||||
* action is the call to the compar function, a considerable optimization
|
||||
* in the average case can be achieved due to the fact that k, the displaced
|
||||
* element, is usually quite small, so it would be preferable to first
|
||||
* heapify, always maintaining the invariant that the larger child is copied
|
||||
* over its parent's record.
|
||||
*
|
||||
* Then, starting from the *bottom* of the heap, finding k's correct place,
|
||||
* again maintaining the invariant. As a result of the invariant no element
|
||||
* is 'lost' when k is assigned its correct place in the heap.
|
||||
*
|
||||
* The time savings from this optimization are on the order of 15-20% for the
|
||||
* average case. See Knuth, Vol. 3, page 158, problem 18.
|
||||
*
|
||||
* XXX Don't break the #define SELECT line, below. Reiser cpp gets upset.
|
||||
*/
|
||||
#define SELECT(par_i, child_i, nmemb, par, child, size, k, count, tmp1, tmp2) { \
|
||||
for (par_i = 1; (child_i = par_i * 2) <= nmemb; par_i = child_i) { \
|
||||
child = base + child_i * size; \
|
||||
if (child_i < nmemb && compar(child, child + size, z) < 0) { \
|
||||
child += size; \
|
||||
++child_i; \
|
||||
} \
|
||||
par = base + par_i * size; \
|
||||
COPY(par, child, count, size, tmp1, tmp2); \
|
||||
} \
|
||||
for (;;) { \
|
||||
child_i = par_i; \
|
||||
par_i = child_i / 2; \
|
||||
child = base + child_i * size; \
|
||||
par = base + par_i * size; \
|
||||
if (child_i == 1 || compar(k, par, z) < 0) { \
|
||||
COPY(child, k, count, size, tmp1, tmp2); \
|
||||
break; \
|
||||
} \
|
||||
COPY(child, par, count, size, tmp1, tmp2); \
|
||||
} \
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts array w/ optional callback argument.
|
||||
*
|
||||
* @param vbase is base of array
|
||||
* @param nmemb is item count
|
||||
* @param size is item width
|
||||
* @param compar is a callback returning <0, 0, or >0
|
||||
* @param z will optionally be passed as the third argument to cmp
|
||||
* @see heapsort()
|
||||
*/
|
||||
int
|
||||
heapsort_r(void *vbase, size_t nmemb, size_t size,
|
||||
int (*compar)(const void *, const void *, void *), void *z)
|
||||
{
|
||||
size_t cnt, i, j, l;
|
||||
char tmp, *tmp1, *tmp2;
|
||||
char *base, *k, *p, *t;
|
||||
|
||||
if (nmemb <= 1)
|
||||
return (0);
|
||||
|
||||
if (!size)
|
||||
return (einval());
|
||||
|
||||
if ((k = malloc(size)) == NULL)
|
||||
return (-1);
|
||||
|
||||
/*
|
||||
* Items are numbered from 1 to nmemb, so offset from size bytes
|
||||
* below the starting address.
|
||||
*/
|
||||
base = (char *)vbase - size;
|
||||
|
||||
for (l = nmemb / 2 + 1; --l;)
|
||||
CREATE(l, nmemb, i, j, t, p, size, cnt, tmp);
|
||||
|
||||
/*
|
||||
* For each element of the heap, save the largest element into its
|
||||
* final slot, save the displaced element (k), then recreate the
|
||||
* heap.
|
||||
*/
|
||||
while (nmemb > 1) {
|
||||
COPY(k, base + nmemb * size, cnt, size, tmp1, tmp2);
|
||||
COPY(base + nmemb * size, base + size, cnt, size, tmp1, tmp2);
|
||||
--nmemb;
|
||||
SELECT(i, j, nmemb, t, p, size, k, cnt, tmp1, tmp2);
|
||||
}
|
||||
free(k);
|
||||
return (0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts array.
|
||||
*
|
||||
* Runs in O (N lg N), both average and worst. While heapsort is faster
|
||||
* than the worst case of quicksort, the BSD quicksort does median
|
||||
* selection so that the chance of finding a data set that will trigger
|
||||
* the worst case is nonexistent. Heapsort's only advantage over
|
||||
* quicksort is that it requires little additional memory.
|
||||
*
|
||||
* @param vbase is base of array
|
||||
* @param nmemb is item count
|
||||
* @param size is item width
|
||||
* @param compar is a callback returning <0, 0, or >0
|
||||
* @see Knuth, Vol. 3, page 145.
|
||||
* @see heapsort_r()
|
||||
* @see mergesort()
|
||||
* @see qsort()
|
||||
*/
|
||||
int
|
||||
heapsort(void *vbase, size_t nmemb, size_t size,
|
||||
int (*compar)(const void *, const void *))
|
||||
{
|
||||
return heapsort_r(vbase, nmemb, size, (void *)compar, 0);
|
||||
}
|
362
libc/mem/mergesort.c
Normal file
362
libc/mem/mergesort.c
Normal file
|
@ -0,0 +1,362 @@
|
|||
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
|
||||
│vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│
|
||||
╞══════════════════════════════════════════════════════════════════════════════╡
|
||||
│ Copyright (c) 1991, 1993 │
|
||||
│ The Regents of the University of California. All rights reserved. │
|
||||
│ │
|
||||
│ Redistribution and use in source and binary forms, with or without │
|
||||
│ modification, are permitted provided that the following conditions │
|
||||
│ are met: │
|
||||
│ 1. Redistributions of source code must retain the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer. │
|
||||
│ 2. Redistributions in binary form must reproduce the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer in the │
|
||||
│ documentation and/or other materials provided with the distribution. │
|
||||
│ 3. Neither the name of the University nor the names of its contributors │
|
||||
│ may be used to endorse or promote products derived from this software │
|
||||
│ without specific prior written permission. │
|
||||
│ │
|
||||
│ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │
|
||||
│ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │
|
||||
│ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │
|
||||
│ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │
|
||||
│ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │
|
||||
│ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │
|
||||
│ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │
|
||||
│ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │
|
||||
│ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │
|
||||
│ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │
|
||||
│ SUCH DAMAGE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/mem/alg.h"
|
||||
#include "libc/mem/mem.h"
|
||||
#include "libc/str/str.h"
|
||||
#include "libc/sysv/errfuns.h"
|
||||
// clang-format off
|
||||
|
||||
asm(".ident\t\"\\n\\n\
|
||||
OpenBSD Sorting (BSD-3)\\n\
|
||||
Copyright 1993 The Regents of the University of California\"");
|
||||
asm(".include \"libc/disclaimer.inc\"");
|
||||
|
||||
/*
|
||||
* Hybrid exponential search/linear search merge sort with hybrid
|
||||
* natural/pairwise first pass. Requires about .3% more comparisons
|
||||
* for random data than LSMS with pairwise first pass alone.
|
||||
* It works for objects as small as two bytes.
|
||||
*/
|
||||
|
||||
#define NATURAL
|
||||
#define THRESHOLD 16 /* Best choice for natural merge cut-off. */
|
||||
|
||||
/* #define NATURAL to get hybrid natural merge.
|
||||
* (The default is pairwise merging.)
|
||||
*/
|
||||
|
||||
static void setup(uint8_t *, uint8_t *, size_t, size_t, int (*)(), void *);
|
||||
static void insertionsort(uint8_t *, size_t, size_t, int (*)(), void *);
|
||||
|
||||
#define ISIZE sizeof(int)
|
||||
#define PSIZE sizeof(uint8_t *)
|
||||
#define ICOPY_LIST(src, dst, last) \
|
||||
do \
|
||||
*(int*)dst = *(int*)src, src += ISIZE, dst += ISIZE; \
|
||||
while(src < last)
|
||||
#define ICOPY_ELT(src, dst, i) \
|
||||
do \
|
||||
*(int*) dst = *(int*) src, src += ISIZE, dst += ISIZE; \
|
||||
while (i -= ISIZE)
|
||||
|
||||
#define CCOPY_LIST(src, dst, last) \
|
||||
do \
|
||||
*dst++ = *src++; \
|
||||
while (src < last)
|
||||
#define CCOPY_ELT(src, dst, i) \
|
||||
do \
|
||||
*dst++ = *src++; \
|
||||
while (i -= 1)
|
||||
|
||||
/*
|
||||
* Find the next possible pointer head. (Trickery for forcing an array
|
||||
* to do double duty as a linked list when objects do not align with word
|
||||
* boundaries.
|
||||
*/
|
||||
/* Assumption: PSIZE is a power of 2. */
|
||||
#define EVAL(p) (uint8_t **) \
|
||||
((uint8_t *)0 + \
|
||||
(((uint8_t *)p + PSIZE - 1 - (uint8_t *) 0) & ~(PSIZE - 1)))
|
||||
|
||||
/**
|
||||
* Sorts array.
|
||||
*
|
||||
* @param vbase is base of array
|
||||
* @param nmemb is item count
|
||||
* @param size is item width
|
||||
* @param cmp is a callback returning <0, 0, or >0
|
||||
* @see mergesort_r()
|
||||
* @see heapsort()
|
||||
* @see qsort()
|
||||
*/
|
||||
int
|
||||
mergesort(void *base, size_t nmemb, size_t size,
|
||||
int (*cmp)(const void *, const void *))
|
||||
{
|
||||
return mergesort_r(base, nmemb, size, (void *)cmp, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts array w/ optional callback argument.
|
||||
*
|
||||
* @param base is base of array
|
||||
* @param nmemb is item count
|
||||
* @param size is item width
|
||||
* @param cmp is a callback returning <0, 0, or >0
|
||||
* @param z will optionally be passed as the third argument to cmp
|
||||
* @see mergesort()
|
||||
*/
|
||||
int
|
||||
mergesort_r(void *base, size_t nmemb, size_t size,
|
||||
int (*cmp)(const void *, const void *, void *), void *z)
|
||||
{
|
||||
int i, sense;
|
||||
int big, iflag;
|
||||
uint8_t *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
|
||||
uint8_t *list2, *list1, *p2, *p, *last, **p1;
|
||||
|
||||
if (size < PSIZE / 2) /* Pointers must fit into 2 * size. */
|
||||
return (einval());
|
||||
|
||||
if (nmemb == 0)
|
||||
return (0);
|
||||
|
||||
/*
|
||||
* XXX
|
||||
* Stupid subtraction for the Cray.
|
||||
*/
|
||||
iflag = 0;
|
||||
if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
|
||||
iflag = 1;
|
||||
|
||||
if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
|
||||
return (-1);
|
||||
|
||||
list1 = base;
|
||||
setup(list1, list2, nmemb, size, cmp, z);
|
||||
last = list2 + nmemb * size;
|
||||
i = big = 0;
|
||||
while (*EVAL(list2) != last) {
|
||||
l2 = list1;
|
||||
p1 = EVAL(list1);
|
||||
for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
|
||||
p2 = *EVAL(p2);
|
||||
f1 = l2;
|
||||
f2 = l1 = list1 + (p2 - list2);
|
||||
if (p2 != last)
|
||||
p2 = *EVAL(p2);
|
||||
l2 = list1 + (p2 - list2);
|
||||
while (f1 < l1 && f2 < l2) {
|
||||
if ((*cmp)(f1, f2, z) <= 0) {
|
||||
q = f2;
|
||||
b = f1, t = l1;
|
||||
sense = -1;
|
||||
} else {
|
||||
q = f1;
|
||||
b = f2, t = l2;
|
||||
sense = 0;
|
||||
}
|
||||
if (!big) { /* here i = 0 */
|
||||
while ((b += size) < t && cmp(q, b, z) >sense)
|
||||
if (++i == 6) {
|
||||
big = 1;
|
||||
goto EXPONENTIAL;
|
||||
}
|
||||
} else {
|
||||
EXPONENTIAL: for (i = size; ; i <<= 1)
|
||||
if ((p = (b + i)) >= t) {
|
||||
if ((p = t - size) > b &&
|
||||
(*cmp)(q, p, z) <= sense)
|
||||
t = p;
|
||||
else
|
||||
b = p;
|
||||
break;
|
||||
} else if ((*cmp)(q, p, z) <= sense) {
|
||||
t = p;
|
||||
if (i == size)
|
||||
big = 0;
|
||||
goto FASTCASE;
|
||||
} else
|
||||
b = p;
|
||||
while (t > b+size) {
|
||||
i = (((t - b) / size) >> 1) * size;
|
||||
if ((*cmp)(q, p = b + i, z) <= sense)
|
||||
t = p;
|
||||
else
|
||||
b = p;
|
||||
}
|
||||
goto COPY;
|
||||
FASTCASE: while (i > size)
|
||||
if ((*cmp)(q, p = b + (i >>= 1), z)
|
||||
<= sense)
|
||||
t = p;
|
||||
else
|
||||
b = p;
|
||||
COPY: b = t;
|
||||
}
|
||||
i = size;
|
||||
if (q == f1) {
|
||||
if (iflag) {
|
||||
ICOPY_LIST(f2, tp2, b);
|
||||
ICOPY_ELT(f1, tp2, i);
|
||||
} else {
|
||||
CCOPY_LIST(f2, tp2, b);
|
||||
CCOPY_ELT(f1, tp2, i);
|
||||
}
|
||||
} else {
|
||||
if (iflag) {
|
||||
ICOPY_LIST(f1, tp2, b);
|
||||
ICOPY_ELT(f2, tp2, i);
|
||||
} else {
|
||||
CCOPY_LIST(f1, tp2, b);
|
||||
CCOPY_ELT(f2, tp2, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (f2 < l2) {
|
||||
if (iflag)
|
||||
ICOPY_LIST(f2, tp2, l2);
|
||||
else
|
||||
CCOPY_LIST(f2, tp2, l2);
|
||||
} else if (f1 < l1) {
|
||||
if (iflag)
|
||||
ICOPY_LIST(f1, tp2, l1);
|
||||
else
|
||||
CCOPY_LIST(f1, tp2, l1);
|
||||
}
|
||||
*p1 = l2;
|
||||
}
|
||||
tp2 = list1; /* swap list1, list2 */
|
||||
list1 = list2;
|
||||
list2 = tp2;
|
||||
last = list2 + nmemb*size;
|
||||
}
|
||||
if (base == list2) {
|
||||
memmove(list2, list1, nmemb*size);
|
||||
list2 = list1;
|
||||
}
|
||||
free(list2);
|
||||
return (0);
|
||||
}
|
||||
|
||||
#define swap(a, b) { \
|
||||
s = b; \
|
||||
i = size; \
|
||||
do { \
|
||||
tmp = *a; *a++ = *s; *s++ = tmp; \
|
||||
} while (--i); \
|
||||
a -= size; \
|
||||
}
|
||||
#define reverse(bot, top) { \
|
||||
s = top; \
|
||||
do { \
|
||||
i = size; \
|
||||
do { \
|
||||
tmp = *bot; *bot++ = *s; *s++ = tmp; \
|
||||
} while (--i); \
|
||||
s -= size2; \
|
||||
} while(bot < s); \
|
||||
}
|
||||
|
||||
/*
|
||||
* Optional hybrid natural/pairwise first pass. Eats up list1 in runs of
|
||||
* increasing order, list2 in a corresponding linked list. Checks for runs
|
||||
* when THRESHOLD/2 pairs compare with same sense. (Only used when NATURAL
|
||||
* is defined. Otherwise simple pairwise merging is used.)
|
||||
*/
|
||||
void
|
||||
setup(uint8_t *list1, uint8_t *list2, size_t n, size_t size,
|
||||
int (*cmp)(const void *, const void *, void *), void *z)
|
||||
{
|
||||
int i, length, size2, sense;
|
||||
uint8_t tmp, *f1, *f2, *s, *l2, *last, *p2;
|
||||
|
||||
size2 = size*2;
|
||||
if (n <= 5) {
|
||||
insertionsort(list1, n, size, cmp, z);
|
||||
*EVAL(list2) = (uint8_t*) list2 + n*size;
|
||||
return;
|
||||
}
|
||||
/*
|
||||
* Avoid running pointers out of bounds; limit n to evens
|
||||
* for simplicity.
|
||||
*/
|
||||
i = 4 + (n & 1);
|
||||
insertionsort(list1 + (n - i) * size, i, size, cmp, z);
|
||||
last = list1 + size * (n - i);
|
||||
*EVAL(list2 + (last - list1)) = list2 + n * size;
|
||||
|
||||
#ifdef NATURAL
|
||||
p2 = list2;
|
||||
f1 = list1;
|
||||
sense = (cmp(f1, f1 + size, z) > 0);
|
||||
for (; f1 < last; sense = !sense) {
|
||||
length = 2;
|
||||
/* Find pairs with same sense. */
|
||||
for (f2 = f1 + size2; f2 < last; f2 += size2) {
|
||||
if ((cmp(f2, f2+ size, z) > 0) != sense)
|
||||
break;
|
||||
length += 2;
|
||||
}
|
||||
if (length < THRESHOLD) { /* Pairwise merge */
|
||||
do {
|
||||
p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
|
||||
if (sense > 0)
|
||||
swap (f1, f1 + size);
|
||||
} while ((f1 += size2) < f2);
|
||||
} else { /* Natural merge */
|
||||
l2 = f2;
|
||||
for (f2 = f1 + size2; f2 < l2; f2 += size2) {
|
||||
if ((cmp(f2-size, f2, z) > 0) != sense) {
|
||||
p2 = *EVAL(p2) = f2 - list1 + list2;
|
||||
if (sense > 0)
|
||||
reverse(f1, f2-size);
|
||||
f1 = f2;
|
||||
}
|
||||
}
|
||||
if (sense > 0)
|
||||
reverse (f1, f2-size);
|
||||
f1 = f2;
|
||||
if (f2 < last || cmp(f2 - size, f2, z) > 0)
|
||||
p2 = *EVAL(p2) = f2 - list1 + list2;
|
||||
else
|
||||
p2 = *EVAL(p2) = list2 + n*size;
|
||||
}
|
||||
}
|
||||
#else /* pairwise merge only. */
|
||||
for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
|
||||
p2 = *EVAL(p2) = p2 + size2;
|
||||
if (cmp (f1, f1 + size, z) > 0)
|
||||
swap(f1, f1 + size);
|
||||
}
|
||||
#endif /* NATURAL */
|
||||
}
|
||||
|
||||
/*
|
||||
* This is to avoid out-of-bounds addresses in sorting the
|
||||
* last 4 elements.
|
||||
*/
|
||||
static void
|
||||
insertionsort(uint8_t *a, size_t n, size_t size,
|
||||
int (*cmp)(const void *, const void *, void *), void *z)
|
||||
{
|
||||
uint8_t *ai, *s, *t, *u, tmp;
|
||||
int i;
|
||||
|
||||
for (ai = a+size; --n >= 1; ai += size)
|
||||
for (t = ai; t > a; t -= size) {
|
||||
u = t - size;
|
||||
if (cmp(u, t, z) <= 0)
|
||||
break;
|
||||
swap(u, t);
|
||||
}
|
||||
}
|
292
libc/mem/qsort.c
Normal file
292
libc/mem/qsort.c
Normal file
|
@ -0,0 +1,292 @@
|
|||
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│
|
||||
│vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│
|
||||
╞══════════════════════════════════════════════════════════════════════════════╡
|
||||
│ Copyright (c) 1991, 1993 │
|
||||
│ The Regents of the University of California. All rights reserved. │
|
||||
│ │
|
||||
│ Redistribution and use in source and binary forms, with or without │
|
||||
│ modification, are permitted provided that the following conditions │
|
||||
│ are met: │
|
||||
│ 1. Redistributions of source code must retain the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer. │
|
||||
│ 2. Redistributions in binary form must reproduce the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer in the │
|
||||
│ documentation and/or other materials provided with the distribution. │
|
||||
│ 3. Neither the name of the University nor the names of its contributors │
|
||||
│ may be used to endorse or promote products derived from this software │
|
||||
│ without specific prior written permission. │
|
||||
│ │
|
||||
│ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │
|
||||
│ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │
|
||||
│ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │
|
||||
│ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │
|
||||
│ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │
|
||||
│ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │
|
||||
│ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │
|
||||
│ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │
|
||||
│ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │
|
||||
│ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │
|
||||
│ SUCH DAMAGE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/mem/alg.h"
|
||||
#include "libc/str/str.h"
|
||||
// clang-format off
|
||||
|
||||
asm(".ident\t\"\\n\\n\
|
||||
OpenBSD Sorting (BSD-3)\\n\
|
||||
Copyright 1993 The Regents of the University of California\"");
|
||||
asm(".include \"libc/disclaimer.inc\"");
|
||||
|
||||
#define CMPPAR int (*cmp)(const void *, const void *, void *),void *arg
|
||||
#define CMPARG cmp, arg
|
||||
#define CMP(a, b) cmp(a, b, arg)
|
||||
#define min(a, b) (a) < (b) ? a : b
|
||||
|
||||
static inline char *med3(char *, char *, char *, CMPPAR);
|
||||
static inline void swapfunc(char *, char *, size_t, int);
|
||||
|
||||
/*
|
||||
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
|
||||
*
|
||||
* This version differs from Bentley & McIlroy in the following ways:
|
||||
* 1. The partition value is swapped into a[0] instead of being
|
||||
* stored out of line.
|
||||
*
|
||||
* 2. The swap function can swap 32-bit aligned elements on 64-bit
|
||||
* platforms instead of swapping them as byte-aligned.
|
||||
*
|
||||
* 3. It uses David Musser's introsort algorithm to fall back to
|
||||
* heapsort(3) when the recursion depth reaches 2*lg(n + 1).
|
||||
* This avoids quicksort's quadratic behavior for pathological
|
||||
* input without appreciably changing the average run time.
|
||||
*
|
||||
* 4. Tail recursion is eliminated when sorting the larger of two
|
||||
* subpartitions to save stack space.
|
||||
*/
|
||||
#define SWAPTYPE_BYTEV 1
|
||||
#define SWAPTYPE_INTV 2
|
||||
#define SWAPTYPE_LONGV 3
|
||||
#define SWAPTYPE_INT 4
|
||||
#define SWAPTYPE_LONG 5
|
||||
|
||||
#define TYPE_ALIGNED(TYPE, a, es) \
|
||||
(((char *)a - (char *)0) % sizeof(TYPE) == 0 && es % sizeof(TYPE) == 0)
|
||||
|
||||
#define swapcode(TYPE, parmi, parmj, n) { \
|
||||
size_t i = (n) / sizeof (TYPE); \
|
||||
TYPE *pi = (TYPE *) (parmi); \
|
||||
TYPE *pj = (TYPE *) (parmj); \
|
||||
do { \
|
||||
TYPE t = *pi; \
|
||||
*pi++ = *pj; \
|
||||
*pj++ = t; \
|
||||
} while (--i > 0); \
|
||||
}
|
||||
|
||||
static inline void
|
||||
swapfunc(char *a, char *b, size_t n, int swaptype)
|
||||
{
|
||||
switch (swaptype) {
|
||||
case SWAPTYPE_INT:
|
||||
case SWAPTYPE_INTV:
|
||||
swapcode(int, a, b, n);
|
||||
break;
|
||||
case SWAPTYPE_LONG:
|
||||
case SWAPTYPE_LONGV:
|
||||
swapcode(long, a, b, n);
|
||||
break;
|
||||
default:
|
||||
swapcode(char, a, b, n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#define swap(a, b) do { \
|
||||
switch (swaptype) { \
|
||||
case SWAPTYPE_INT: { \
|
||||
int t = *(int *)(a); \
|
||||
*(int *)(a) = *(int *)(b); \
|
||||
*(int *)(b) = t; \
|
||||
break; \
|
||||
} \
|
||||
case SWAPTYPE_LONG: { \
|
||||
long t = *(long *)(a); \
|
||||
*(long *)(a) = *(long *)(b); \
|
||||
*(long *)(b) = t; \
|
||||
break; \
|
||||
} \
|
||||
default: \
|
||||
swapfunc(a, b, es, swaptype); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype)
|
||||
|
||||
static inline char *
|
||||
med3(char *a, char *b, char *c, CMPPAR)
|
||||
{
|
||||
return CMP(a, b) < 0 ?
|
||||
(CMP(b, c) < 0 ? b : (CMP(a, c) < 0 ? c : a ))
|
||||
:(CMP(b, c) > 0 ? b : (CMP(a, c) < 0 ? a : c ));
|
||||
}
|
||||
|
||||
static void
|
||||
introsort(char *a, size_t n, size_t es, size_t maxdepth, int swaptype, CMPPAR)
|
||||
{
|
||||
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
|
||||
int cmp_result;
|
||||
size_t r, s;
|
||||
|
||||
loop: if (n < 7) {
|
||||
for (pm = a + es; pm < a + n * es; pm += es)
|
||||
for (pl = pm; pl > a && CMP(pl - es, pl) > 0;
|
||||
pl -= es)
|
||||
swap(pl, pl - es);
|
||||
return;
|
||||
}
|
||||
if (maxdepth == 0) {
|
||||
if (heapsort_r(a, n, es, CMPARG) == 0)
|
||||
return;
|
||||
}
|
||||
maxdepth--;
|
||||
pm = a + (n / 2) * es;
|
||||
if (n > 7) {
|
||||
pl = a;
|
||||
pn = a + (n - 1) * es;
|
||||
if (n > 40) {
|
||||
s = (n / 8) * es;
|
||||
pl = med3(pl, pl + s, pl + 2 * s, CMPARG);
|
||||
pm = med3(pm - s, pm, pm + s, CMPARG);
|
||||
pn = med3(pn - 2 * s, pn - s, pn, CMPARG);
|
||||
}
|
||||
pm = med3(pl, pm, pn, CMPARG);
|
||||
}
|
||||
swap(a, pm);
|
||||
pa = pb = a + es;
|
||||
pc = pd = a + (n - 1) * es;
|
||||
for (;;) {
|
||||
while (pb <= pc && (cmp_result = CMP(pb, a)) <= 0) {
|
||||
if (cmp_result == 0) {
|
||||
swap(pa, pb);
|
||||
pa += es;
|
||||
}
|
||||
pb += es;
|
||||
}
|
||||
while (pb <= pc && (cmp_result = CMP(pc, a)) >= 0) {
|
||||
if (cmp_result == 0) {
|
||||
swap(pc, pd);
|
||||
pd -= es;
|
||||
}
|
||||
pc -= es;
|
||||
}
|
||||
if (pb > pc)
|
||||
break;
|
||||
swap(pb, pc);
|
||||
pb += es;
|
||||
pc -= es;
|
||||
}
|
||||
|
||||
pn = a + n * es;
|
||||
r = min(pa - a, pb - pa);
|
||||
vecswap(a, pb - r, r);
|
||||
r = min(pd - pc, pn - pd - es);
|
||||
vecswap(pb, pn - r, r);
|
||||
/*
|
||||
* To save stack space we sort the smaller side of the partition first
|
||||
* using recursion and eliminate tail recursion for the larger side.
|
||||
*/
|
||||
r = pb - pa;
|
||||
s = pd - pc;
|
||||
if (r < s) {
|
||||
/* Recurse for 1st side, iterate for 2nd side. */
|
||||
if (s > es) {
|
||||
if (r > es) {
|
||||
introsort(a, r / es, es, maxdepth,
|
||||
swaptype, CMPARG);
|
||||
}
|
||||
a = pn - s;
|
||||
n = s / es;
|
||||
goto loop;
|
||||
}
|
||||
} else {
|
||||
/* Recurse for 2nd side, iterate for 1st side. */
|
||||
if (r > es) {
|
||||
if (s > es) {
|
||||
introsort(pn - s, s / es, es, maxdepth,
|
||||
swaptype, CMPARG);
|
||||
}
|
||||
n = r / es;
|
||||
goto loop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts array w/ optional callback parameter.
|
||||
*
|
||||
* @param a is base of array
|
||||
* @param n is item count
|
||||
* @param es is item width
|
||||
* @param cmp is a callback returning <0, 0, or >0
|
||||
* @param arg is passed to callback
|
||||
* @see qsort()
|
||||
*/
|
||||
void
|
||||
qsort_r(void *a, size_t n, size_t es,
|
||||
int (*cmp)(const void *, const void *, void *), void *arg)
|
||||
{
|
||||
size_t i, maxdepth = 0;
|
||||
int swaptype;
|
||||
|
||||
/* Approximate 2*ceil(lg(n + 1)) */
|
||||
for (i = n; i > 0; i >>= 1)
|
||||
maxdepth++;
|
||||
maxdepth *= 2;
|
||||
|
||||
if (TYPE_ALIGNED(long, a, es))
|
||||
swaptype = es == sizeof(long) ? SWAPTYPE_LONG : SWAPTYPE_LONGV;
|
||||
else if (sizeof(int) != sizeof(long) && TYPE_ALIGNED(int, a, es))
|
||||
swaptype = es == sizeof(int) ? SWAPTYPE_INT : SWAPTYPE_INTV;
|
||||
else
|
||||
swaptype = SWAPTYPE_BYTEV;
|
||||
|
||||
introsort(a, n, es, maxdepth, swaptype, CMPARG);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts array.
|
||||
*
|
||||
* This implementation uses the Quicksort routine from Bentley &
|
||||
* McIlroy's "Engineering a Sort Function", 1992, Bell Labs.
|
||||
*
|
||||
* This version differs from Bentley & McIlroy in the following ways:
|
||||
*
|
||||
* 1. The partition value is swapped into a[0] instead of being stored
|
||||
* out of line.
|
||||
*
|
||||
* 2. The swap function can swap 32-bit aligned elements on 64-bit
|
||||
* platforms instead of swapping them as byte-aligned.
|
||||
*
|
||||
* 3. It uses David Musser's introsort algorithm to fall back to
|
||||
* heapsort(3) when the recursion depth reaches 2*lg(n + 1). This
|
||||
* avoids quicksort's quadratic behavior for pathological input
|
||||
* without appreciably changing the average run time.
|
||||
*
|
||||
* 4. Tail recursion is eliminated when sorting the larger of two
|
||||
* subpartitions to save stack space.
|
||||
*
|
||||
* @param a is base of array
|
||||
* @param n is item count
|
||||
* @param es is item width
|
||||
* @param cmp is a callback returning <0, 0, or >0
|
||||
* @see mergesort()
|
||||
* @see heapsort()
|
||||
* @see qsort_r()
|
||||
* @see djbsort()
|
||||
*/
|
||||
void
|
||||
qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *))
|
||||
{
|
||||
qsort_r(a, n, es, (void *)cmp, 0);
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
|
||||
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
|
||||
╞══════════════════════════════════════════════════════════════════════════════╡
|
||||
│ Copyright 2022 Justine Alexandra Roberts Tunney │
|
||||
│ │
|
||||
│ Permission to use, copy, modify, and/or distribute this software for │
|
||||
│ any purpose with or without fee is hereby granted, provided that the │
|
||||
│ above copyright notice and this permission notice appear in all copies. │
|
||||
│ │
|
||||
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
|
||||
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
|
||||
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
|
||||
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
|
||||
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
|
||||
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
|
||||
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
|
||||
│ PERFORMANCE OF THIS SOFTWARE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/mem/alg.h"
|
||||
|
||||
/**
|
||||
* Sorts array.
|
||||
*
|
||||
* This implementation uses the Quicksort routine from Bentley &
|
||||
* McIlroy's "Engineering a Sort Function", 1992, Bell Labs.
|
||||
*
|
||||
* @param base points to an array to sort in-place
|
||||
* @param count is the item count
|
||||
* @param width is the size of each item
|
||||
* @param cmp is a callback returning <0, 0, or >0
|
||||
* @see smoothsort()
|
||||
* @see djbsort()
|
||||
*/
|
||||
void qsort(void *a, size_t n, size_t es,
|
||||
int (*cmp)(const void *, const void *)) {
|
||||
qsort_r(a, n, es, (void *)cmp, 0);
|
||||
}
|
|
@ -1,178 +0,0 @@
|
|||
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
|
||||
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
|
||||
╞══════════════════════════════════════════════════════════════════════════════╡
|
||||
│ Copyright (c) 1992, 1993 │
|
||||
│ The Regents of the University of California. All rights reserved. │
|
||||
│ │
|
||||
│ Redistribution and use in source and binary forms, with or without │
|
||||
│ modification, are permitted provided that the following conditions │
|
||||
│ are met: │
|
||||
│ 1. Redistributions of source code must retain the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer. │
|
||||
│ 2. Redistributions in binary form must reproduce the above copyright │
|
||||
│ notice, this list of conditions and the following disclaimer in the │
|
||||
│ documentation and/or other materials provided with the distribution. │
|
||||
│ 3. Neither the name of the University nor the names of its contributors │
|
||||
│ may be used to endorse or promote products derived from this software │
|
||||
│ without specific prior written permission. │
|
||||
│ │
|
||||
│ THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND │
|
||||
│ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE │
|
||||
│ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE │
|
||||
│ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE │
|
||||
│ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL │
|
||||
│ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS │
|
||||
│ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) │
|
||||
│ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT │
|
||||
│ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY │
|
||||
│ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF │
|
||||
│ SUCH DAMAGE. │
|
||||
╚─────────────────────────────────────────────────────────────────────────────*/
|
||||
#include "libc/macros.internal.h"
|
||||
#include "libc/mem/alg.h"
|
||||
#include "libc/str/str.h"
|
||||
|
||||
asm(".ident\t\"\\n\\n\
|
||||
NetBSD qsort (BSD-3)\\n\
|
||||
Copyright 1992 The Regents of the University of California\"");
|
||||
asm(".include \"libc/disclaimer.inc\"");
|
||||
|
||||
#define SWAPINIT(a, es) \
|
||||
swaptype = ((char *)a - (char *)0) % sizeof(long) || es % sizeof(long) ? 2 \
|
||||
: es == sizeof(long) ? 0 \
|
||||
: 1;
|
||||
|
||||
#define swapcode(TYPE, parmi, parmj, n) \
|
||||
size_t i = (n) / sizeof(TYPE); \
|
||||
TYPE *pi = (TYPE *)(void *)(parmi); \
|
||||
TYPE *pj = (TYPE *)(void *)(parmj); \
|
||||
do { \
|
||||
TYPE t = *pi; \
|
||||
*pi++ = *pj; \
|
||||
*pj++ = t; \
|
||||
} while (--i > 0)
|
||||
|
||||
#define swap(a, b) \
|
||||
if (swaptype == 0) { \
|
||||
long t = *(long *)(void *)(a); \
|
||||
*(long *)(void *)(a) = *(long *)(void *)(b); \
|
||||
*(long *)(void *)(b) = t; \
|
||||
} else \
|
||||
swapfunc(a, b, es, swaptype)
|
||||
|
||||
#define vecswap(a, b, n) \
|
||||
if ((n) > 0) swapfunc((a), (b), (size_t)(n), swaptype)
|
||||
|
||||
static inline void swapfunc(char *a, char *b, size_t n, int swaptype) {
|
||||
if (swaptype <= 1) {
|
||||
swapcode(long, a, b, n);
|
||||
} else {
|
||||
swapcode(char, a, b, n);
|
||||
}
|
||||
}
|
||||
|
||||
static inline char *med3(char *a, char *b, char *c,
|
||||
int (*cmp)(const void *, const void *, void *),
|
||||
void *z) {
|
||||
if (cmp(a, b, z) < 0) {
|
||||
return cmp(b, c, z) < 0 ? b : (cmp(a, c, z) < 0 ? c : a);
|
||||
} else {
|
||||
return cmp(b, c, z) > 0 ? b : (cmp(a, c, z) < 0 ? a : c);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts array.
|
||||
*
|
||||
* This implementation uses the Quicksort routine from Bentley &
|
||||
* McIlroy's "Engineering a Sort Function", 1992, Bell Labs. This
|
||||
* implementation is also used on systems like NetBSD and MacOS.
|
||||
*
|
||||
* @param a is base which points to an array to sort in-place
|
||||
* @param n is item count
|
||||
* @param es is width of each item
|
||||
* @param cmp is a callback returning <0, 0, or >0
|
||||
* @param arg will optionally be passed as the third argument to cmp
|
||||
* @see smoothsort_r()
|
||||
*/
|
||||
void qsort_r(void *a, size_t n, size_t es,
|
||||
int (*cmp)(const void *, const void *, void *), void *arg) {
|
||||
size_t d, r, s;
|
||||
int swaptype, cmp_result;
|
||||
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
|
||||
|
||||
loop:
|
||||
SWAPINIT(a, es);
|
||||
if (n < 7) {
|
||||
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
|
||||
for (pl = pm; pl > (char *)a && cmp(pl - es, pl, arg) > 0; pl -= es)
|
||||
swap(pl, pl - es);
|
||||
return;
|
||||
}
|
||||
|
||||
pm = (char *)a + (n / 2) * es;
|
||||
if (n > 7) {
|
||||
pl = (char *)a;
|
||||
pn = (char *)a + (n - 1) * es;
|
||||
if (n > 40) {
|
||||
d = (n / 8) * es;
|
||||
pl = med3(pl, pl + d, pl + 2 * d, cmp, arg);
|
||||
pm = med3(pm - d, pm, pm + d, cmp, arg);
|
||||
pn = med3(pn - 2 * d, pn - d, pn, cmp, arg);
|
||||
}
|
||||
pm = med3(pl, pm, pn, cmp, arg);
|
||||
}
|
||||
swap(a, pm);
|
||||
pa = pb = (char *)a + es;
|
||||
pc = pd = (char *)a + (n - 1) * es;
|
||||
|
||||
for (;;) {
|
||||
while (pb <= pc && (cmp_result = cmp(pb, a, arg)) <= 0) {
|
||||
if (cmp_result == 0) {
|
||||
swap(pa, pb);
|
||||
pa += es;
|
||||
}
|
||||
pb += es;
|
||||
}
|
||||
while (pb <= pc && (cmp_result = cmp(pc, a, arg)) >= 0) {
|
||||
if (cmp_result == 0) {
|
||||
swap(pc, pd);
|
||||
pd -= es;
|
||||
}
|
||||
pc -= es;
|
||||
}
|
||||
if (pb > pc) break;
|
||||
swap(pb, pc);
|
||||
pb += es;
|
||||
pc -= es;
|
||||
}
|
||||
|
||||
pn = (char *)a + n * es;
|
||||
r = MIN(pa - (char *)a, pb - pa);
|
||||
vecswap(a, pb - r, r);
|
||||
r = MIN((size_t)(pd - pc), pn - pd - es);
|
||||
vecswap(pb, pn - r, r);
|
||||
|
||||
/*
|
||||
* To save stack space we sort the smaller side of the partition first
|
||||
* using recursion and eliminate tail recursion for the larger side.
|
||||
*/
|
||||
r = pb - pa;
|
||||
s = pd - pc;
|
||||
if (r < s) {
|
||||
/* Recurse for 1st side, iterate for 2nd side. */
|
||||
if (s > es) {
|
||||
if (r > es) qsort_r(a, r / es, es, cmp, arg);
|
||||
a = pn - s;
|
||||
n = s / es;
|
||||
goto loop;
|
||||
}
|
||||
} else {
|
||||
/* Recurse for 2nd side, iterate for 1st side. */
|
||||
if (r > es) {
|
||||
if (s > es) qsort_r(pn - s, s / es, es, cmp, arg);
|
||||
n = r / es;
|
||||
goto loop;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -50,6 +50,42 @@ TEST(qsort, test) {
|
|||
free(M);
|
||||
}
|
||||
|
||||
BENCH(qsort, equivalence_random) {
|
||||
size_t i;
|
||||
size_t n = 1000;
|
||||
long *a = gc(malloc(n * sizeof(long)));
|
||||
long *b = gc(malloc(n * sizeof(long)));
|
||||
long *c = gc(malloc(n * sizeof(long)));
|
||||
for (i = 0; i < n; ++i) a[i] = lemur64();
|
||||
memcpy(b, a, n * sizeof(long));
|
||||
memcpy(c, a, n * sizeof(long));
|
||||
qsort(b, n, sizeof(long), CompareLong);
|
||||
heapsort(c, n, sizeof(long), CompareLong);
|
||||
ASSERT_EQ(0, memcmp(b, c, n * sizeof(long)));
|
||||
mergesort(c, n, sizeof(long), CompareLong);
|
||||
ASSERT_EQ(0, memcmp(b, c, n * sizeof(long)));
|
||||
smoothsort(c, n, sizeof(long), CompareLong);
|
||||
ASSERT_EQ(0, memcmp(b, c, n * sizeof(long)));
|
||||
}
|
||||
|
||||
BENCH(qsort, equivalence_reverse) {
|
||||
size_t i;
|
||||
size_t n = 1000;
|
||||
long *a = gc(malloc(n * sizeof(long)));
|
||||
long *b = gc(malloc(n * sizeof(long)));
|
||||
long *c = gc(malloc(n * sizeof(long)));
|
||||
for (i = 0; i < n; ++i) a[n - i - 1] = i;
|
||||
memcpy(b, a, n * sizeof(long));
|
||||
memcpy(c, a, n * sizeof(long));
|
||||
qsort(b, n, sizeof(long), CompareLong);
|
||||
heapsort(c, n, sizeof(long), CompareLong);
|
||||
ASSERT_EQ(0, memcmp(b, c, n * sizeof(long)));
|
||||
mergesort(c, n, sizeof(long), CompareLong);
|
||||
ASSERT_EQ(0, memcmp(b, c, n * sizeof(long)));
|
||||
smoothsort(c, n, sizeof(long), CompareLong);
|
||||
ASSERT_EQ(0, memcmp(b, c, n * sizeof(long)));
|
||||
}
|
||||
|
||||
BENCH(qsort, bench) {
|
||||
size_t i;
|
||||
size_t n = 1000;
|
||||
|
@ -60,6 +96,10 @@ BENCH(qsort, bench) {
|
|||
for (i = 0; i < n; ++i) p1[i] = i + ((lemur64() % 3) - 1);
|
||||
EZBENCH2("qsort nearly", memcpy(p2, p1, n * sizeof(long)),
|
||||
qsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("heapsort nearly", memcpy(p2, p1, n * sizeof(long)),
|
||||
heapsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("mergesort nearly", memcpy(p2, p1, n * sizeof(long)),
|
||||
mergesort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("smoothsort nearly", memcpy(p2, p1, n * sizeof(long)),
|
||||
smoothsort(p2, n, sizeof(long), CompareLong));
|
||||
|
||||
|
@ -67,6 +107,10 @@ BENCH(qsort, bench) {
|
|||
for (i = 0; i < n; ++i) p1[i] = n - i;
|
||||
EZBENCH2("qsort reverse", memcpy(p2, p1, n * sizeof(long)),
|
||||
qsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("heapsort reverse", memcpy(p2, p1, n * sizeof(long)),
|
||||
heapsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("mergesort reverse", memcpy(p2, p1, n * sizeof(long)),
|
||||
mergesort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("smoothsort reverse", memcpy(p2, p1, n * sizeof(long)),
|
||||
smoothsort(p2, n, sizeof(long), CompareLong));
|
||||
|
||||
|
@ -74,6 +118,10 @@ BENCH(qsort, bench) {
|
|||
rngset(p1, n * sizeof(long), 0, 0);
|
||||
EZBENCH2("qsort random", memcpy(p2, p1, n * sizeof(long)),
|
||||
qsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("heapsort random", memcpy(p2, p1, n * sizeof(long)),
|
||||
heapsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("mergesort random", memcpy(p2, p1, n * sizeof(long)),
|
||||
mergesort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("smoothsort random", memcpy(p2, p1, n * sizeof(long)),
|
||||
smoothsort(p2, n, sizeof(long), CompareLong));
|
||||
|
||||
|
@ -84,6 +132,10 @@ BENCH(qsort, bench) {
|
|||
}
|
||||
EZBENCH2("qsort 2n", memcpy(p2, p1, n * sizeof(long)),
|
||||
qsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("heapsort 2n", memcpy(p2, p1, n * sizeof(long)),
|
||||
heapsort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("mergesort 2n", memcpy(p2, p1, n * sizeof(long)),
|
||||
mergesort(p2, n, sizeof(long), CompareLong));
|
||||
EZBENCH2("smoothsort 2n", memcpy(p2, p1, n * sizeof(long)),
|
||||
smoothsort(p2, n, sizeof(long), CompareLong));
|
||||
}
|
Loading…
Add table
Reference in a new issue