Lecture 2 Complexity Analysis Sorting
Lecture 2 Complexity Analysis Sorting
Sorting Algorithms
23 78 45 8 32 56 Original List
23 78 45 8 32 56 After pass 1
23 45 78 8 32 56 After pass 2
After pass 3
8 23 45 78 32 56
8 23 32 45 78 56 After pass 4
After pass 5
8 23 32 45 56 78
Cs 405 Analysis of Algorithms
Insertion Sort Algorithm
template <class Item>
void insertionSort(Item a[], int n)
{
for (int i = 1; i < n; i++)
{
Item tmp = a[i];
8 23 32 45 56 78 Original List
8 23 32 45 56 78 pass 1, no move
8 23 32 45 56 78 pass 2, no move
pass 3, no move
8 23 32 45 56 78
8 23 32 45 56 78 pass 4, no move
pass 5, no move
8 23 32 45 56 78
78 56 45 32 23 12 Original List
56 78 45 32 23 12 pass 1, 1 move
45 56 78 32 23 12 pass 2, 2 moves
pass 3, 3 moves
32 45 56 78 23 12
23 32 45 56 78 12 pass 4, 4 moves
pass 5, 5 moves
12 23 32 45 56 78
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
3 6 1 9 4 5 2 7
merge merge
1 3 6 9 merge
2 4 5 7
1 2 3 4 5 6 7 9
Mergesort Example2
Mergesort Analysis of Merge
A worst-case instance of the merge step in mergesort:
Maximum possible key comparisons are there.
Mergesort Analysis of Merge (cont.)
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, comparisons, etc: 2k + 2k
In general, main steps: ck
Worst-case:
The number of moves, comparisons, etc: 2k + 2k
In general, main steps: ck
20 20
................. level m: no merger = 0
Mergesort - Analysis
Worst-case
The number of key comparisons, moves, copy, etc:
= c2m+ c2m+ + c2m ( m terms )
= cm*2m
Remember, n = 2m. So, m = log2 n
= c log2n n
O (n log2n )
Arranging the array elements around the pivot p generates two smaller sorting
problems.
sort the left section of the array, and sort the right section of the array.
when these two smaller sorting problems are solved recursively, our bigger
sorting problem is solved.