Download presentation
Presentation is loading. Please wait.
1
CS 280 Data Structures Professor John Peterson
2
Example: log(N) This is where things get hairy! How would you compute Log 10 (N) in a very approximate manner? What does “Log(N)” mean mathematically? How might we get this in a real piece of code? Why don’t we really need to know the base of the logarithm?
3
Log Complexity int j = n; while (j > 0) { System.out.println(j); j = j / 2; /* Integer division! */ } What would this print for n = 10? 100?
4
Example public void r(int i) { if (i == 0) return; System.out.print(i) r(i-1); r(i-1); } r(n)
5
Example: 2 N public void r(int i) { if (i == 0) return; System.out.print(i) r(i-1); r(i-1); } r(n)
6
Dominating Terms The big idea behind Big-O notation is that when you add complexities, one term may dominate the other. That is, once n has reached some value, one complexity is ALWAYS bigger than another. Example: O(n 2 ) + O(n) = O(n 2 + n) = O(n 2 )
7
A Complexity Ladder O(1) O(log(n)) O(n) O(n log(n)) O(n 2 ) O(2 n ) There are lots more complexities “between the cracks” but these are the ones that we’ll be seeing this term.
8
Homework Let’s have a look …
9
Demo: Excel Complexity.xls
10
Insertion Sort Complexity What is the complexity of insertion sort? insertionSort(array A) for i <- 1 to length[A]-1 do value <- A[i] j <- i-1 while j >= 0 and A[j] > value do A[j + 1] = A[j]; j <- j-1 A[j+1] <- value t
11
Selection Sort Here’s another sort algorithm: Void selectSort(Sortable s) { for (int i = 0; i < s.size()-1; i++) for (int j = i+1; j < s.size(); j++) if (s.gtr(i,j)) s.swap(i,j); } What is the complexity here in the best and worst cases?
12
Dictionary Lookup Suppose we know that array a is in sorted order: Boolean present(key,a) { int low = 0; int high = a.length-1; while (low <= high) { int mid = (low + high)/2; if (a[mid] == key) return true; if (a[mid] < key) low = mid + 1 else high = mid-1 } return false; } What is this complexity of this? Why?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.