Fall2022_Week1.2
Fall2022_Week1.2
Algorithms
Notes by: Sharma Thankachan
Instructor: Charles Hughes
Week 1.2: Getting Started
(Simple Sorts)
2
The Sorting Problem
3
Insertion Sort
• Operates in n rounds
Swap towards left side ;
• At the kth round, Stop until seeing an item
with a smaller value.
……
kth item
5
Selection Sort Timing
• Best case is worst case as always
search remaining list for smallest
• All cases are
• Takes n-1 + n-2 + n-3 + … + 1
• Again, the known sum = n (n-1) / 2
• Thus, all cases have an n2 dominant term
6
Divide and Conquer
• Divide a big problem into smaller problems
è solve smaller problems separately
è combine the results to solve original one
7
Divide-and-Conquer for Sorting
• What is a smaller problem ?
è E.g., sorting fewer numbers
è Let’s divide the list to two shorter lists
• Next, solve smaller problems (how?)
10
Analyzing the Running Times
• Suppose that our algorithms are now
described in terms of RAM operations
è we can count # of each operation used
è we can measure the running time !
11
Insertion Sort (Running Time)
The following is a pseudo-code for Insertion Sort.
Each line requires constant RAM operations.
15
Worst-Case Running Time
• In our course (and in most CS research),
we concentrate on worst-case time
• Some reasons for this:
1. Gives an upper bound of running time
2. Worst case occurs fairly often
Remark: Some people also study average-case
running time (they assume input is
drawn randomly)
16
Try this at home
• Revisit pseudo-code for Insertion Sort
– make sure you understand what’s going on
17
Merge Sort (Running Time)
The following is a partial pseudo-code for Merge Sort.
19
Merge Sort (Running Time)
T(n) = 2T(n/2) + c1n + c2 when n > 1
T(1) = c3
Solving the recurrence, we have
T(n) = 4 T(N/4) + 2 c1n + 2c2
T(n) = 2kT(n/2k) + k c1n + kc2
Let k = lg n
T(n) = 2lg n T(n/2lg n) + k c1n + kc2
T(n) = n T(1) + c1 n lg n + c2 lg n
T(n) = c3 n + c1 n lg n + c2 lg n
T(n) = c1 n lg n + a linear term + a lg term
20
Which Algorithm is Faster?
• Unfortunately, we still cannot tell
– since constants in running times are unknown
21