CSE 40872 Lecture 009

Topic:Sorting (C)
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 21, 2009

Sorting

QuickSort

  1. Pick an element, called a pivot, from the list.

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.

  1. Recursively sort sub-lists of lesser and greater elements.

O(nlogn) on average, but O(n2) in worst-case.

Qsort

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.

Qsort Examples

// 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);

MergeSort

  1. If the list is of length 0 or 1, then it is already sorted. Otherwise:
  2. Divide the unsorted list into two sublists of about half the size.
  3. Sort each sublist recursively by re-applying merge sort.
  4. Merge the two sublists back into one sorted list.

Works really well with linked lists.

MergeSort Properties

Summary

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.