Chapter # 4 Sorting Algorithms
Chapter # 4 Sorting Algorithms
Analysis of Algorithm
Chapter 4
Sorting Algorithms
(Elementary Sort Algorithms)
1
4/26/2020
Other Resources
Animated Sorting Examples
http://www.ee.ryerson.ca/~courses/coe428/intro/introduction.html
Analysis of Algorithm
2
4/26/2020
Sorting by Comparison
The Sorting by Comparison method sorts input
By comparing pairs of keys in the input.
Elementary Algorithms
Are inefficient but easy to implement
Their running times are θ(n2)
Common algorithms are
Insertion sort, Exchange sort, Selection sort
Advanced Algorithms
Advanced algorithms are efficient
Implementations are usually based on recursive function calls
Their running times are θ(n lg n)
The typical advanced algorithms include
Merge sort, Quick sort, Heap sort
Analysis of Algorithm
Insertion Sort
3
4/26/2020
Insertion Sort
The key is compared with the successive elements on the left
Until a smaller element is found
Key is inserted
By shifting all the elements to right
Analysis of Algorithm
Insertion Sort
Illustration
Analysis of Algorithm
4
4/26/2020
Insertion Sort
Analysis of Algorithm
n
C5 tj
j 2
n
C6
j 2
(t j 1)
n
C7
j 2
(t j 1)
C8 n–1
T (n) c1 c2 n c3 (n 1) c4 (n 1) c5 t j c6 t j 1 c7 t j 1 c8 (n 1)
n n n
j 2 j 2 j 2
Analysis of Algorithm
5
4/26/2020
Illustration
Next slide
Analysis of Algorithm
6
4/26/2020
Illustration
Next slide
Analysis of Algorithm
7
4/26/2020
Analysis of Algorithm
8
4/26/2020
Analysis of Algorithm
Selection Sort
9
4/26/2020
Selection Sort
The main Idea
Find the smallest element in the array
Exchange it with the element in the first position
Find the second smallest element and exchange it with the
element in the second position
Continue until the array is sorted
Disadvantage:
Running time depends only slightly on the of order in the
file
Analysis of Algorithm
Analysis of Algorithm
10
4/26/2020
n - 1 repetitions required
Last element is automatically sorted
Analysis of Algorithm
n 1 n 1 n 1
T (n) c1 c2 n c3 (n 1) c4 (n j 1) c5 n j c6 n j c7 (n 1) (n 2 )
j 1 j 1 j 2
Analysis of Algorithm
11
4/26/2020
Analysis of Algorithm
Homework
Analyze the
The selection sort for all three cases
Analysis of Algorithm
12