• Stars
    star
    458
  • Rank 95,591 (Top 2 %)
  • Language
    C
  • License
    MIT License
  • Created about 14 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Sorting routine implementations in "template" C

sort.h

Overview

sort.h is an implementation of a ton of sorting algorithms in C with a user-defined type that is provided at include time.

This means you don't have to pay the function call overhead of using a standard library routine. This also gives us the power of higher-level language generics.

In addition, you don't have to link in a library: the entirety of this sorting library is contained in the sort.h header file.

You get the choice of many sorting routines, including:

  • Timsort (stable)
  • Quicksort
  • Merge sort (stable)
  • In-place merge sort (not stable)
  • Shellsort
  • Binary insertion sort
  • Heapsort

If you set SORT_EXTRA and have sort_extra.h available in the path, there are some additional, specialized sorting routines available:

If you don't know which one to use, you should probably use Timsort.

If you have a lot data that is semi-structured, then you should definitely use Timsort.

If you have data that is really and truly random, quicksort is probably fastest.

Usage

To use this library, you need to do three things:

  • #define SORT_TYPE to be the type of the elements of the array you want to sort. (For pointers, you should declare this like: #define SORT_TYPE int*)
  • #define SORT_NAME to be a unique name that will be prepended to all the routines, i.e., #define SORT_NAME mine would give you routines named mine_heap_sort, and so forth.
  • #include "sort.h". Make sure that sort.h is in your include path.

Then, enjoy using the sorting routines.

Quick example:

#define SORT_NAME int64
#define SORT_TYPE int64_t
#define SORT_CMP(x, y) ((x) - (y))
#include "sort.h"

You would now have access to int64_quick_sort, int64_tim_sort, etc., which you can use like

/* Assumes you have some int64_t *arr or int64_t arr[128]; */
int64_quick_sort(arr, 128);

See demo.c for a more detailed example usage.

If you are going to use your own custom type, you must redefine SORT_CMP(x, y) with your comparison function, so that it returns a value less than zero if x < y, equal to zero if x == y, and greater than 0 if x > y.

The default just uses the builtin < operators:

#define SORT_CMP(x, y)  ((x) < (y) ? -1 : ((y) < (x) ? 1 : 0))

It is often just fine to just subtract the arguments as well (though this can cause some stability problems with floating-point types):

#define SORT_CMP(x, y) ((x) - (y))

You can also redefine TIM_SORT_STACK_SIZE (default 128) to control the size of the tim sort stack (which can be used to reduce memory). Reducing it too far can cause tim sort to overflow the stack though.

You can specify definitions for all functions that are included in sort.h. Making sort functions static increases the likelihood a compiler will eliminate dead code.

#define SORT_DEF static

Speed of routines

The speed of each routine is highly dependent on your computer and the structure of your data.

If your data has a lot of partially sorted sequences, then Tim sort will beat the kilt off of anything else.

Timsort is not as good if memory movement is many orders of magnitude more expensive than comparisons (like, many more than for normal int and double). If so, then quick sort is probably your routine. On the other hand, Timsort does extremely well if the comparison operator is very expensive, since it strives hard to minimize comparisons.

Here is the output of demo.c, which will give you the timings for a run of 10,000 int64_ts on 2014-era MacBook Pro:

Running tests
stdlib qsort time:             1285.00 us per iteration
stdlib heapsort time:          2109.00 us per iteration
stdlib mergesort time:         1299.00 us per iteration
quick sort time:                579.00 us per iteration
selection sort time:         127176.00 us per iteration
merge sort time:                999.00 us per iteration
binary insertion sort time:   13443.00 us per iteration
heap sort time:                 592.00 us per iteration
shell sort time:               1054.00 us per iteration
tim sort time:                 1005.00 us per iteration
in-place merge sort time:       903.00 us per iteration
grail sort time:               1220.00 us per iteration
sqrt sort time:                1095.00 us per iteration

Quicksort is the winner here. Heapsort, in-place merge sort, and timsort also often tend to be quite fast.

Contributing

See CONTRIBUTING.md.

References

License

Available under the MIT License. See LICENSE.md for details.

More Repositories

1

vector.h

C header library for typed lists (using macros and "template" C).
C
44
star
2

ace_spell_check_js

Add spell checking in the Ace JS editor
JavaScript
25
star
3

python-xr

Python source code cross reference
HTML
15
star
4

scanty_wordpress_import

Import Wordpress XML files into Scanty
Ruby
12
star
5

jtux

Patched version of jtux library
C
8
star
6

aesrng

AES-based random number generator in C
C
8
star
7

ttyrec2gif

Convert ttyrec files to animated gifs
Python
7
star
8

atom-jsonpp

Atom editor JSON pretty printer
CoffeeScript
6
star
9

cpython-internals

CPython Internals talk from PyCon AU 2016
CSS
5
star
10

docker-ghost

Run ghost blogging platform in a Docker container.
Shell
5
star
11

adventure-talk-pycon

TeX
4
star
12

lords-of-cyberspace

Lords of Cyberspace source
C
4
star
13

mcrypt

mcrypt snapshot http://mcrypt.sourceforge.net/
Shell
4
star
14

littlereader

Small, single-user RSS reader
Go
3
star
15

sagewiki

Tools for the Sage wiki
Python
3
star
16

cray-blitz

Cray Blitz Chess Engine
Fortran
3
star
17

intermediate_python

An Intermediate Python Coursebook
Python
3
star
18

adventwure

Adventure for Twilio!
Python
3
star
19

docker-sage

Docker container for Sage
Shell
2
star
20

adventure-talk

Colossal Cave Adventure in Python talk from North Bay Python 2017
JavaScript
2
star
21

keysafe

A simple way to encrypt multiple files for multiple users using keybase.io
Python
2
star
22

rubyzipload

Loads ZIP code and US location information from US Census into a database
2
star
23

zelda-randomizer-helper

Zelda Randomizer Map Helper
CSS
2
star
24

projectpier

Project Pier fork (to add templating)
PHP
2
star
25

slacker

Slacker is a simple Slack bot library written in Go.
Go
2
star
26

sublime_whitespace

Only trim trailing whitespace on new lines.
Python
2
star
27

screenrun

Send a terminal session to the web
Go
2
star
28

goconf

A configuration file template for Go
Go
2
star
29

dotfiles

My dotfiles
Vim Script
2
star
30

python_remote_debugger

A remote debugging protocol and implementation in Python.
Python
2
star
31

atom-gofmt

Gofmt plugin for the Atom editor
CoffeeScript
1
star
32

wavegaming

Google Wave tools and gadgets for board gaming
1
star
33

shortcodes

URL shortening codes from a random number generator
Python
1
star
34

fairygloss

Updated fork of sailorhg/fairyfloss
CSS
1
star
35

pywasm

Python
1
star
36

t-essentials

Terra Essentials main repository.
Ruby
1
star
37

pizza

Pizza -- a dumb geocoding system based on US Census data.
Scala
1
star
38

chapel_libs

Chapel libraries and miscellaneous files
Vim Script
1
star
39

adventurejs

Colossal Cave Adventure (1977)
JavaScript
1
star
40

binary_matrix

Rust implementation of dense binary matrices and vectors.
Rust
1
star
41

rust-qsieve

Rust implementation of the Quadratic Sieve
Rust
1
star
42

sage_sliderepl

sliderepl hack that works with Sage
Python
1
star
43

math-ruining-everything-since-forever

Talk presented at ConFoo: "Math: Ruining Everything Since Forever"
Python
1
star
44

tito-zapier

ti.to webhook to zapier connector using AWS Lambda
Python
1
star
45

mfa-talk-pycon-au-2018

MFA Talk from PyCon AU 2018
TeX
1
star
46

solarjs

Javascript model of the solar system
JavaScript
1
star
47

findimagedupes

Finds similar and duplicate images.
Go
1
star
48

sobg

Science of Board Games code
Python
1
star