7 Sorting
7 Sorting
CS 201
Importance of sorting
Why don’t CS profs ever stop talking about sorting?
1. Computers spend more time sorting than anything else, historically 25% on
mainframes.
2. Sorting is the best studied problem in computer science, with a variety of
different algorithms known.
3. Most of the interesting ideas we will encounter in the course can be taught in
the context of sorting, such as divide-and-conquer, randomized algorithms,
and lower bounds.
2
Sorting
● Organize data into ascending / descending order
○ Useful in many applications
○ Any examples can you think of?
3
Efficiency of sorting
● Sorting is important because once a set of items is sorted, many other
problems become easy.
● Furthermore, using O(n log n) sorting algorithms leads naturally to
sub-quadratic algorithms for these problems.
● Large-scale data processing would be impossible if sorting took O(n2) time.
4
Applications of sorting
● Closest pair: Given n numbers, find the pair which are closest to each other.
○ Once the numbers are sorted, the closest pair will be next to each other in sorted order, so an
O(n) linear scan completes the job.
● Element uniqueness: Given a set of n items, are they all unique or are there
any duplicates?
○ Sort them and do a linear scan to check all adjacent pairs.
○ This is a special case of closest pair above.
○ Complexity?
● Mode: Given a set of n items, which element occurs the largest number of
times? More generally, compute the frequency distribution.
○ How would you solve it?
5
Sorting algorithms
● There are many sorting algorithms, such as:
○ Selection Sort
○ Insertion Sort
○ Bubble Sort
○ Merge Sort
○ Quick Sort
● First three sorting algorithms are not so efficient, but the last two are efficient
sorting algorithms.
6
Selection sort
● List divided into two sublists, sorted and unsorted.
● Find the biggest element from the unsorted sublist. Swap it with the element
at the end of the unsorted data.
● After each selection and swapping, imaginary wall between the two sublists
move one element back.
● Sort pass: Each time we move one element from the unsorted sublist to the
sorted sublist, we say that we have completed a sort pass.
8
Selection sort
typedef type-of-array-item DataType;
9
Selection sort
int indexOfLargest(const DataType theArray[], int size) {
int indexSoFar = 0;
for (int currentIndex=1; currentIndex<size;++currentIndex){
if (theArray[currentIndex] > theArray[indexSoFar])
indexSoFar = currentIndex;
}
return indexSoFar;
}
--------------------------------------------------------
void swap(DataType &x, DataType &y) {
DataType temp = x;
x = y;
y = temp;
}
10
Selection sort - analysis
● To analyze sorting, count simple operations.
● For sorting, important simple operations: key comparisons and number of
moves.
● In selectionSort() function, the for loop executes n-1 times.
● In selectionSort() function, we invoke swap() once at each iteration.
→ Total Swaps: n-1
→ Total Moves: 3*(n-1) (Each swap has three moves)
11
Selection sort - analysis
● In indexOfLargest() function, the for loop executes (for each size from n to 2),
and in each iteration we make one key comparison.
→ # of key comparisons = n-1 + n-2 + … + 2 + 1 = (n-1)*n/2
→ So, Selection sort is O(n2)
● The best case, worst case, and average case are the same → all O(n2)
○ Meaning: behavior of selection sort does not depend on initial organization of data.
○ Since O(n2) grows so rapidly, the selection sort algorithm is appropriate only for small n.
● Although selection sort requires O(n2) key comparisons, it only requires O(n)
moves.
○ Selection sort is good choice if data moves are costly but key comparisons are not costly
(short keys, long records).
12
Insertion sort
● Insertion sort is a simple sorting algorithm appropriate for small inputs.
○ Most common sorting technique used by card players.
● In each pass, the first element of the unsorted part is picked up, transferred to
the sorted sublist, and inserted in place.
13
Insertion sort
● Assume input array: A[1..n]
● Iterate j from 2 to n
already sorted
j
iter j
j
after
iter j
sorted subarray
14
Insertion sort
Insertion-Sort (A)
1. for j ← 2 to n do
2. key ← A[j];
3. i ← j - 1;
4. while i > 0 and A[i] > key
do
5. A[i+1] ← A[i];
6. i ← i - 1;
endwhile
7. A[i+1] ← key;
endfor
15
Insertion sort
Insertion-Sort (A)
1. for j ← 2 to n do
Iterate over array elements j
2. key ← A[j];
3. i ← j - 1;
4. while i > 0 and A[i] > key Loop invariant:
The subarray A[1..j-1]
do is always sorted
5. A[i+1] ← A[i];
6. i ← i - 1; already sorted
j
endwhile
7. A[i+1] ← key;
endfor
key
16
Insertion sort
Insertion-Sort (A)
1. for j ← 2 to n do
2. key ← A[j];
3. i ← j - 1;
Shift right the entries
4. while i > 0 and A[i] > key in A[1..j-1] that are > key
do
5. A[i+1] ← A[i]; already sorted
j
6. i ← i - 1; < key > key
endwhile
j
7. A[i+1] ← key; < key > key
endfor
17
Insertion sort
Insertion-Sort (A)
1. for j ← 2 to n do
key
2. key ← A[j];
3. i ← j - 1;
4. while i > 0 and A[i] > key j
do < key > key
● Incremental approach
○ Having sorted A[1..j-1], place A[j] correctly so that A[1..j] is sorted
27
Insertion sort
void insertionSort(DataType theArray[], int n) {
theArray[loc] = nextItem;
}
}
28
Insertion sort
Sorted Unsorted
29
Insertion sort - analysis
● What is the complexity of insertion sort? → Depends on array contents
● Best-case: → O(n)
○ Array is already sorted in ascending order.
○ Inner loop will not be executed.
○ The number of moves: 2*(n-1) → O(n)
○ The number of key comparisons: (n-1) → O(n)
● Worst-case: → O(n2)
○ Array is in reverse order.
○ Inner loop is executed p-1 times, for p = 2,3, …, n
○ The number of moves: 2*(n-1)+(1+2+...+n-1)= 2*(n-1)+ n*(n-1)/2 → O(n2)
○ The number of key comparisons: (1+2+...+n-1)= n*(n-1)/2 → O(n2)
● Average-case: → O(n2)
○ We have to look at all possible initial data organizations.
● So, Insertion Sort is O(n2) 30
Insertion sort - analysis
● Which running time will be used to characterize this algorithm?
○ Best, worst or average?
→ Worst case:
○ Longest running time (this is the upper limit for the algorithm)
○ It is guaranteed that the algorithm will not be worse than this.
31
Bubble sort
● List divided into two sublists: sorted and unsorted.
● The largest element is bubbled from the unsorted list and moved to the sorted
sublist.
● After that, the wall moves one element back, increasing the number of sorted
elements and decreasing the number of unsorted ones.
● One sort pass: each time an element moves from the unsorted part to the
sorted part.
● Given a list of n elements, bubble sort requires up to n-1 passes (maximum
passes) to sort data.
32
Bubble sort
33
Bubble sort
void bubbleSort(DataType theArray[], int n) {
bool sorted = false;
● It is a recursive algorithm.
○ Divide the list into halves,
○ Sort each half separately, and
○ Then merge the sorted halves into one sorted array.
36
Merge sort - basic idea
Input array A
Divide
sort this half sort this half
Conquer
37
Merge sort
Merge-Sort (A, p, r)
if p = r then return;
else
q ← ⎣ (p+r)/2 ⎦; (Divide)
Merge-Sort (A, p, q); (Conquer)
Merge-Sort (A, q+1, r); (Conquer)
Merge (A, p, q, r); (Combine)
endif
38
Merge sort - example
Merge-Sort (A, p, r) p q r
if p = r then 5 2 4 6 1 3
return p q r
else
q ← ⎣ (p+r)/2 ⎦ 2 4 5 1 3 6
Merge-Sort (A, p, q)
Merge-Sort (A, q+1, r) 1 2 3 4 5 6
Merge(A, p, q, r)
endif
39
How to merge 2 sorted subarrays?
A[p..q] 2 4 5
1 2 3 4 5 6
A[q+1..r] 1 3 6
40
Merge sort - correctness
Merge-Sort (A, p, r) Base case: p = r
→Trivially correct
if p = r then
return Inductive hypothesis: Merge-Sort
else is correct for any subarray that is a
q ← ⎣ (p+r)/2 ⎦ strict (smaller) subset of A[p, r].
42
Merge sort
void mergesort(DataType theArray[], int first, int last) {
if (first < last) {
43
Merge
const int MAX_SIZE = maximum-number-of-items-in-array;
} // end merge
45
Merge sort - another example
6 3 9 1 5 4 7 2
divide
6 3 9 1 5 4 7 2
divide divide
6 3 9 1 5 4 7 2
47
Merge sort - analysis of merge
A worst-case instance of the merge step in mergesort
48
Merge sort - analysis of merge
0 k-1 0 k-1
Merging two sorted arrays of size k .......... ..........
0 2k-1
..........
● Best-case:
○ All the elements in the first array are smaller (or larger) than all the elements in the second
array.
○ The number of moves: 2k + 2k
○ The number of key comparisons: k
● Worst-case:
○ The number of moves: 2k + 2k
○ The number of key comparisons: 2k-1
49
Merge sort - complexity
Merge-Sort (A, p, r) T(n)
if p = r then
return Θ(1)
else
q ← ⎣ (p+r)/2 ⎦ Θ(1)
Merge(A, p, q, r) Θ(n)
endif
50
Merge sort - recurrence
● Describe a function recursively in terms of itself
● To analyze the performance of recursive algorithms
Θ(1) if n=1
T(n) =
2T(n/2) + Θ(n) otherwise
51
How to solve for T(n)?
● Generally, we will assume T(n) = Θ(1) for sufficiently small n
52
Solve recurrence: T(n) = 2T(n/2) + Θ(n)
Θ(n)
T(n/2) T(n/2)
53
Solve recurrence: T(n) = 2T(n/2) + Θ(n)
Θ(n)
Θ(n/2) Θ(n/2)
T(n/2)
each size
subprobs
halved
2x
54
Solve recurrence: T(n) = 2T(n/2) + Θ(n)
Θ(n) Θ(n)
Θ(1) Θ(1) Θ(1) Θ(1) Θ(1) Θ(1) Θ(1) Θ(1) Θ(1) Θ(n)
Θ(n) Total: Θ(nlgn)
55
Merge sort - analysis
56
Merge sort - analysis
57
Merge sort - analysis
● Worst-case:
The number of key comparisons:
= m*2m –
= n * log2n – n + 1
→ O (n * log2n)
58
Merge sort - analysis
● There are possibilities when merging two sorted lists of size k.
→ O (n * log2n )
59
Merge sort - analysis
● Merge sort is an extremely efficient algorithm with respect to time.
○ Both worst-case and average-case are O (n * log2n)
● But, merge sort requires an extra array whose size equals to the size of the
original array.
60
Quick sort
● Like Merge sort, Quick sort is based on divide-and-conquer paradigm.
● Algorithm
1. First, partition an array into two parts.
2. Then, sort each part independently.
3. Finally, combine sorted parts by a simple concatenation.
61
Quick sort
The Quick sort algorithm consists of the following three steps:
62
Partition
● Partitioning places the pivot in its correct position within the array.
63
Divide: partition the array around a pivot element
1. Choose a pivot element x
2. Rearrange the array such that:
Left subarray: All elements < x
Right subarray: All elements ≥ x
Input: 5 3 2 7 4 1 3 6 e.g. x = 5
After partitioning: 3 3 2 1 4 5 7 6
<5 ≥5
64
Conquer: recursively sort the subarrays
Note: Everything in the left subarray < everything in the right subarray
3 3 2 1 4 5 7 6
After conquer: 1 2 3 3 4 5 6 7
65
Partition - choosing the pivot
● First, select a pivot element among the elements of the given array, and put
the pivot into the first location of the array before partitioning.
66
Partition function
Initial state of the array
67
Partition function
Invariant for the partition algorithm
68
Partition function
Moving theArray[firstUnknown] into S1 by swapping it with
theArray[lastS1+1] and by incrementing both lastS1 and firstUnknown.
69
Partition function
Moving theArray[firstUnknown] into S2 by incrementing firstUnknown.
70
Partition function
Developing the first partition
of an array when the pivot is
the first item
71
Quick sort function
void quicksort(DataType theArray[], int first, int last) {
// Precondition: theArray[first..last] is an array.
// Postcondition: theArray[first..last] is sorted.
int pivotIndex;
73
Partition function
// initially, everything but pivot is in unknown
int lastS1 = first; // index of last item in S1
int firstUnknown = first + 1; // index of first item in unknown
75
Quick sort - analysis
● Quick sort is O(n*log2n) in the best case and average case.
● Quick sort is slow when the array is already sorted and we choose the first
element as the pivot.
76
Quick sort - analysis
A worst-case partitioning with quicksort
77
Quick sort - analysis
An average-case partitioning with quicksort
78
Other sorting algorithms?
Many! For example:
● Radix sort
● Shell sort
● Comb sort
● Heapsort
● Counting sort
● Bucket sort
● Distribution sort
● Timsort
● Radix sort :
○ Treats each data item as a character string.
○ First, group data items according to their rightmost character, and put these groups into order
w.r.t. this rightmost character.
○ Then, combine these groups.
○ Repeat these grouping and combining operations for all other character positions in the data
items from the rightmost to the leftmost character position.
80
Radix sort - example
81
Radix sort - example
mom, dad, god, fat, bad, cat, mad, pat, bar, him original list
(dad,god,bad,mad) (mom,him) (bar) (fat,cat,pat) group strings by rightmost letter
dad,god,bad,mad,mom,him,bar,fat,cat,pat combine groups
(dad,bad,mad,bar,fat,cat,pat) (him) (god,mom) group strings by middle letter
dad,bad,mad,bar,fat,cat,pat,him,god,mom combine groups
(bad,bar) (cat) (dad) (fat) (god) (him) (mad,mom) (pat) group strings by middle letter
82
Radix sort - algorithm
radixSort(int theArray[], in n:integer, in d:integer)
// sort n d-digit integers in the array theArray
for (j=d down to 1) {
Initialize 10 groups to empty
Initialize a counter for each group to 0
for (i=0 through n-1) {
k = jth digit of theArray[i]
Place theArray[i] at the end of group k
Increase kth counter by 1
}
Replace the items in theArray with all the items in
group 0, followed by all the items in group 1, and so on.
}
83
Radix sort - analysis
● The Radix sort algorithm requires 2*n*d moves to sort n strings of d
characters each.
→ So, Radix sort is O(n)
84
Comparison of sorting algorithms
85