NOTES: we assume that the objects to be sorted have more than one attribute, and one of those attributes is taken to be the "key" (for example we might sort employee records using employee number as the key, or we could sort the same set of records by name of employee, or weight). Also, we generally assume we are sorting into "non-decreasing" order. This is not essentially true, as we could equally well sort the objects in decreasing order (largest first), and it does not change the nature of the problem.
1. Simple sorting schemes, such as
(a) bubble sort
(b) insertion sort
(c) selection sort
These are O(n*n) algorithms
2. Mergesort ... O(n log n)
See source /home/s7/pat/scheme/pub/sort.scm
The merge function takes two sorted lists l1 and l2. At each step merge takes the smaller of the head of l1 and the head of l2, and appends it to a growing list, and removes that element from the list (either l1 or l2).
A merge on lists of length n/2 is O(n).
The running time of mergesort on a list of n elements is then
t(0) = 0
t(1) = 1
t(n) = 2.t(n/2) + c.n
where c.n is the cost of merging two lists of length n/2, and the term
2t(n/2) is the two recursive calls to mergesort with lists l1 and l2
of length n/2. Consequently,
t(n) = 2.t(n/2) + c.n
= 2.(2.t(n/4) + c.n/2) + c.n
= 2.(2.(2.t(n/8) + c.n/4) + c.n/2) + c.n
= 8.t(n/8) + 3.c.n
A pattern emerges, and by induction on i we obtain
t(n) = 2^i.t(n/2^i) + i.c.n
where the operator ^ is "raised to the power". If we assume that n is
a power of 2 (ie 2, 4, 8, 16, 32, ... generally 2^k) the expansion
process comes to an end when we get t(1) on the right, and that occurs
when i=k, whereupon
t(n) = 2^k.t(1) + k.c.n
We have just stated that the process comes to an end when i=k, where
n = 2^k. Put another way, k = log n (to the base 2 of course), therefore
t(n) = n + c.n.log n
= O(n log n)
(draw-position i (vector-ref V i))
on the screen. If all the numbers are sorted into order I will get a
diagonal line. The (bubble-demo n) generates a vector of size n filled
randomly with the first n integers. It then performs a bubble sort on that vector,
redrawing the data after each iteration. You will get a picture of how the sort works, and how order emerges within the vector.