Lecture Sorting
Lecture Sorting
Lecture Sorting
A Guide
Joshua Knowles
School of Computer Science
The University of Manchester
However, you still need to know your way (a little) around the sorting
“jungle”.
Covered in: the course book; labs; this lecture; wikipedia; wider
reading
Quicksort is good
Bucket sort
Counting sort O(n)
Radix sort
Mergesort
Heapsort O(n log n)
Quicksort
Tree sort
Insertion sort
Selection sort O(n2)
Bubble sort
The first three can only be used on special cases though, as we shall see.
Input:
an (ordered) array of keys, array
All keys must be comparable. The keys must form a total order:
If X is totally ordered under ≤, then the following statements hold for all a, b and c in
X:
If a ≤ b and b ≤ a then a = b (antisymmetry);
If a ≤ b and b ≤ c then ≤ c (transitivity);
a ≤ b or b ≤ a (totality).
(Note: an array of items all with the same value is still a total order).
Output:
a sorted array sortedArray such that
Some sorting algorithms have very low overhead, and so they tend to
be very efficient on small input sizes, even if their asymptotic
complexity is poor. Selection sort is like this. It is often used to sort
lists shorter than 16 within a quicksort routine.
Some sorting algorithms perform poorly when many keys in the input
have the same value. Which algorithms? Why? On the other hand,
Bingo sort is a variant of selection sort that is efficient if many values
are duplicates. (see wikipedia)
Bucket sort and Radix sort achieve this lower bound, but only on
restricted inputs.
Joshua Knowles 22 Roscoe Th. B, Nov 26 2010
Lower Bound for
Comparison-Based Sorting
• Quicksort
• Heap sort
Properties
↓
List1: 12 16 19
↓
List2: 11 12 12 35
↓
Output: 11
Compare the two pointed-at values. Copy the smaller one into the
pointed-at place in the output. If the two values compared are equal,
copy the one from List1. Move the pointer of the output, and the input
list we copied from, one place to the right.
↓
List1: 12 16 19
↓
List2: 11 12 12 35
↓
Output: 11 12 12 12 16 19 35
You will use (and possibly implement) a priority queue in the lab on
knapsack problems.
You have already stored dictionary words in a tree to sort them. The
principle is the same.
Properties:
Time complexity is O(n log n) on worst-case inputs
Heap sort can be implemented in-place by implementing the heap
within a portion of the input array
Heap sort is not stable. Why not?
0 7 1 8 2 9 3 10 4 11
piv=11
swap
0 7 1 8 2 9 3 10 4 11
piv=4
swap swap swap
0 3 1 2 4 9 7 10 8 __
piv=2
swap swap
0 1 2 3 __ __ __ __ __ __
piv=1
swap
0 1 __ __ __ __ __ __ __ __
You met bucket sort (or counting sort) in the lab on complexity.
Buckets need not be of size 1. If larger buckets are used (as above),
then an extra sorting procedure can be used to sort the contents of
each bucket.