qsort.c (2052B)
1/*--------------------------------------------------------------------- 2 qsort() - sort an array 3 4 Copyright (C) 2018, Philipp Klaus Krause . krauseph@informatik.uni-freiburg.de 5 6 This library is free software; you can redistribute it and/or modify it 7 under the terms of the GNU General Public License as published by the 8 Free Software Foundation; either version 2, or (at your option) any 9 later version. 10 11 This library is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU General Public License for more details. 15 16 You should have received a copy of the GNU General Public License 17 along with this library; see the file COPYING. If not, write to the 18 Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, 19 MA 02110-1301, USA. 20 21 As a special exception, if you link this library with other files, 22 some of which are compiled with SDCC, to produce an executable, 23 this library does not by itself cause the resulting executable to 24 be covered by the GNU General Public License. This exception does 25 not however invalidate any other reasons why the executable file 26 might be covered by the GNU General Public License. 27-------------------------------------------------------------------------*/ 28 29#include <stdlib.h> 30 31// Despite the name, this is an insertion sort, since it tends to be smaller in code size. 32 33static void swap(void *restrict dst, void *restrict src, size_t n) 34{ 35 unsigned char *restrict d = dst; 36 unsigned char *restrict s = src; 37 38 while(n--) 39 { 40 unsigned char tmp = *d; 41 *d = *s; 42 *s = tmp; 43 d++; 44 s++; 45 } 46} 47 48void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *) __reentrant) 49{ 50 unsigned char *b = base; 51 52 if(nmemb <= 1) 53 return; 54 55 for(unsigned char *i = base; i < b + nmemb * size; i += size) 56 { 57 for(unsigned char *j = i; (j > b) && (*compar)(j, j - size) < 0; j -= size) 58 swap(j, j - size, size); 59 } 60} 61