lect2_Foundations
lect2_Foundations
Algorithms
Lecture 2
Dr. Metwally Rashad
2022
Table of Contents
1. Foundations
- The Role of Algorithms in Computing
- Design and Analysis algorithms
- Growth of Functions
2. Sorting
- Heapsort
- Quicksort
- Sorting in Linear Time
3. Graph Algorithms
- Elementary Graph Algorithms
- Minimum Spanning Trees
4. Advanced Design and Analysis Techniques
- Dynamic Programming
- Greedy Algorithms
5. Selected Topics
- Linear Programming
- String Matching
1/14
Ch1: Foundations 2/14
Designing Divide-and-Conquer Algorithms
Sort 2 8 4 9 3 5 1 6
Merge 2 4 8 9 1 3 5 6
Merge 1 2 3 4 5 6 8 9 5/14
Design Merge Sort Algorithm
Note that:
𝐴[𝑝 … … 𝑟]
𝑛1 =𝐴[𝑝 … . . 𝑞]
𝑛2 = 𝐴[𝑞 + 1 … … 𝑟] 6/14
Merge Sort Example
Example2
7/14
Merge Sort Example (cont.)
8/14
Analyzing Divide-and-Conquer Algorithms
When an algorithm contains a recursive call to itself, we can often
describe its running time by a recurrence equation or recurrence,
which describes the overall running time on a problem of size 𝑛 in terms
of the running time on smaller inputs.
let 𝑻(𝒏) be the running time on a problem of size 𝑛.
If the problem size is small enough, say 𝒏 ≤ 𝒄 for some constant 𝒄, the
straightforward solution takes constant time, which we write as Θ(𝟏)
Suppose that our division of the problem yields 𝒂 subproblems, each of
which is 𝟏/𝒃 the size of the original.
9/14
Analyzing Divide-and-Conquer Algorithms
Takes time 𝑇(𝑛/𝑏) to solve one subproblem of size 𝑛/𝑏, and so it takes
time 𝑎𝑇(𝑛/𝑏) to solve of them.
We take 𝑫(𝒏) time to divide the problem into subproblems and 𝐂(𝒏)
time to combine the solutions to the subproblems into the solution to the
original problem, we get the recurrence
10/14
Analysis of Merge Sort Algorithm
Each divide step then yields two subsequences of size exactly 𝑛/2.
Divide: The divide step just computes the middle of the subarray, which takes
constant time. Thus, 𝑫(𝒏) = Θ(𝟏)
11/14
Recurrence for Merge Sort Algorithm
We shall usually omit stating the base case when 𝑇(𝑛) = Θ(1) for sufficiently small
𝑛, but only when it has no effect on the asymptotic solution to the recurrence.
14/14