Professional Documents
Culture Documents
80-1591947018947-HND PRG W14 Algorithm Efficiency
80-1591947018947-HND PRG W14 Algorithm Efficiency
1
Lesson Learning Outcome
Pass Merit Distinction
2
Algorithm Efficiency
3
Execution Time vs
Algorithm Efficiency
4
Running Time(t) Volume of Data(n)
5
Big-O Notation
6
Best, Worst and Average Case
▪ Best Case – Here we look at the most favourable situation and check the
efficiency of the algorithm. For example, Sorting a nearly sorted array.
▪ Worst Case – Here we look at most adverse situation and analyse the efficiency of
the algorithm. For example, Sorting an array arranged in descending order to
ascending order.
▪ Average Case – This could the average of the best case and the worst case
scenarios
Generally, when comparing the efficiencies of algorithms, we use either the Worst
Case analysis or Average Case analysis because Best Case may not really show big
difference between the good one and the bad one.
7
Linear Search
▪ Example – Searching for Item 17 in the following array (Arrow indicates the
current element being compared).
23 45 28 17 29 13 50 80 65 11
0 1 2 3 4 5 6 7 8 9
Start Stop
8
Linear Search - Efficiency
9
Binary Search
▪ We compare the middle element and continue the search on upper or lower
half or the array based on the value is greater or smaller than the middle.
This continues until the value is found at the middle or until we confirm the
value is not present.
▪ Example – Searching for Item 29 in the following array
Low High
11 13 17 23 28 29 45 50 65 80
0 1 2 3 4 5 6 7 8 9
Mid
10
Binary Search
Mid High
Low
11 13 17 23 28 29 45 50 65 80
0 1 2 3 4 5 6 7 8 9
11
Binary Search - Efficiency
(Log2 n + 1)/2
Average Case Average of the above 2
comparisons
12
Bubble Sort
Initially 9 5 12 7 2 Iteration 1 59 95 12
7 27
12 2
12
0 1 2 3 4
0 1 2 3 4
▪ N – 1 Passes(Iterations)
Iteration 2 5 7
9 27
9 92 12
▪ Target starts from Last
0 1 2 3 4
Element
13
Bubble Sort - Efficiency
1 pass
Already sorted array is given
Best Case n-1 comparisons
for sorting
0 interchanges
n-1 pass
Descending order array is
Worst Case n (n-1)/2 comparisons
given for ascending sort
n (n-1)/2 interchanges
n (n-1)/2 comparisons
Average Case Average of the above 2
n (n-1)/2 interchanges
Big-O Notation = O ( n2 )
14
Lesson Summary
▪ Algorithm Efficiency
▪ Execution time vs Algorithm Efficiency
▪ Running time(t) vs Volume of data(n)
▪ Big-O Notation
▪ Best, Worst and Average Case Analysis
▪ Linear Search Efficiency
▪ Binary Search Efficiency
▪ Bubble Sort Efficiency
15