Topic: | Sorting (C) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 21, 2009 |
2. Reorder the list so that all elements which are less than the pivot come before it and so that all elements greater than the pivot come after it.
O(nlogn) on average, but O(n2) in worst-case.
stdlib.h provides quick sort function qsort which will sort an array:
void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));
base = pointer to start of array
nmemb = number of elements in array
size = size of each element in array
compar = comparison function
Implementation is normally in-place, highly optimized, and unstable.
// Sort argv
qsort(argv, argc, sizeof(char *), strcmp);
struct job { char id; int priority };
static int compare_jobs(const void *a, const void *b) {
struct job *ja = *(struct job **)(a);
struct job *jb = *(struct job **)(b);
return (ja->priority - jb->priority);
}
// Sort jobs
qsort(jobs, njobs, sizeof(struct job *), compare_jobs);
Works really well with linked lists.
In C, qsort is the only built-in sorting function. Unfortunately it only works on arrays and is unstable. Still, for most problems it is enough, you just have define the comparison function.