Professional Documents
Culture Documents
DAA Lecture 3
DAA Lecture 3
Lecture 3
Types by Algorithms
Recursive
Brute force
Divide and Conquer
Dynamic Programming
Greedy
Heuristic
Search etc
Recursive algorithms
8
Search algorithms
10
Types of Analysis
• Worst case (e.g. cards reversely ordered)
– Provides an upper bound on running time
• Average case
– Provides a prediction about the running time
– Assumes that the input is random
(general case)
11
Asymptotic Notations
12
Additional Reading
https://www.codecademy.com/learn/cspath-asymptotic-
notation/modules/cspath-asymptotic-notation/cheatsheet
https://www.geeksforgeeks.org/analysis-of-algorithms-set-
3asymptotic-notations/
https://www.tutorialspoint.com/data_structures_algorithm
s/asymptotic_analysis.htm
https://www.youtube.com/watch?v=7dz8Iaf_weM
13
Logarithms
In algorithm analysis we often use the notation “log n” without
a logb x x logb a
14
Asymptotic Notations - Examples
• For each of the following pairs of functions, either f(n) is O(g(n)), f(n)
is Ω(g(n)), or f(n) = Θ(g(n)).
2n 2 ≤ cn3 2 ≤ cn c = 1 and n = 2
– 2n2 = O(n3): 0
16
Examples
– 5n2 = (n)
c, n0 such that: 0 cn 5n2
cn 5n2
c = 1 and n0 = 1
17
The Sorting Problem
• Input:
• Output:
18
Bubble Sort
• Idea:
– Repeatedly pass through the array
– Swaps adjacent elements that are out of order
i
1 2 3 n
8 4 6 9 2 3 1
j
19
Summary of Steps of Bubble Sort
Compare each pair of adjacent elements from the beginning of an
array and, if they are in reversed order, swap them.
20
Bubble Sort
Alg.: BUBBLESORT(A)
for i 1 to length[A]
do for j 1 to length[A]-i
21
Bubble Sort
Worst case
О(n2)
Best case
О(n2)
Average case
О(n2)
22
Example
Sort the following data using Bubble Sort
8 4 6 9 2 3 1
23
Selection Sort
Summary of Steps
Find the smallest element in the array
24
Selection Sort
The algorithm works as follows:
25
Example
Step 1
8 4 6 9 2 3 1 1 2 3 4 9 6 8
Step 2
1 4 6 9 2 3 8 1 2 3 4 6 9 8
Step 3 Step 7
1 2 6 9 4 3 8 1 2 3 4 6 8 9
Sorted Array
1 2 3 9 4 6 8 1 2 3 4 6 8 9
26
Selection Sort
Alg.: SELECTION-SORT(A)
n ← length[A]
for j ← 1 to n - 1
do smallest ← j
for i ← j + 1 to n
do if A[i] < A[smallest]
then smallest ← i
exchange A[j] ↔ A[smallest]
27
Selection Sort
Worst case
О(n2)
Best case
О(n2)
Average case
О(n2)
28