Download presentation
Presentation is loading. Please wait.
1
CSC 205 Java Programming II
Lecture 24 Algorithm Efficiency
2
Algorithm Analysis Assume two algorithms perform the same task.
Which one do you choose to use? That is, which one is better? Choose the one that is more efficient Runs faster Takes up less space
3
Searching Algorithms Linear search and binary search
Is meerkat in the table? IndexScan TableScan
4
Efficiency Instead of measuring the real run-time, we compare the number of operations Available before running, even writing the program Run-time will be effected by Processor multitasking
5
Linear Search Number of comparisons Worst case: n Best case: 1
int found = -1; for (int i=0; i<a.length; i++) { if (a[i] == key) { found = i; break; } return found;
6
Binary Search Number of comparisons Worst case: Log2(n) Best case: 1
int low = 0; int high = a.length - 1; while (low < high) { int mid = (low + high) / 2; if (a[mid] < key) low = mid + 1; else high = mid; }
7
Big-O Notation Exact number doesn’t matter The search algorithms
Just concern order-of-magnitude O(n) means that f(n) < c*n for n > k, where c and k are both constants The search algorithms Linear search: O(n) (big-O of n) Binary search: O(log n) (big-O of the logarithm of n)
8
Code Idioms & Big-O for (int i=0; i<n; i++) O(n)
for (int i=0; i<n; i++) for (int j=0; j<n; j++) O(n2) for (int i=0; i<n; i++) for (int j=0; j<i; j++) O(n2) for (int i=0; i<n; i++) for (int j=0; j<k; j++) O(n) note: k is a constant
9
Code Idioms & Big-O (cont’d)
S O(1) while (n>1) { n /= 2; S } O(log n) for (int i=0; i<n; i++) while (n>1) { n /= 2; S } O(nlog n)
10
Order Hierarchy O(1)<O(log n) <O(n)<O(n log n)<O(n2)<O(n3)<…<O(2n)
11
Determine Big-O Notation
For the following growth rate functions, give the corresponding Big-O notations n n 7*log2n + n n*log2n + n2
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.