Exam 1 Deck Flashcards
Fibonachi Time Complexity T(n)
If n<= 2 T(n) = 1 ELSE T(n)=2^n+1 - 1
Fibonachi Recursive Relation
T(n)= T(n-1) + T(n-2)
T(n)? Big-0? for(int i = 0; i < n; i++){ for(int j = i+1; j< n; j++){ Simple Statement } }
T(n) = n(n-1)/2 => T(n) = 0.5n^2 - 0.5n
Big 0 => n^2
T(n)? Big-0? for(int i=0; i<=n; i++){ for(int j=1; j<=n; j++) { for(int k=n; k>=1; k--) { sum = i+j+k; cout<< sum << endl; } } }
T(n) = 2 x n x n x (n+1) => 2n^3 + 2n^2
Big 0 => n^3
Master Theorem Case 1:
T(n)=
IF
If ( d > log[b] a )
T(n) = c * n^d
Master Theorem Case 2:
T(n)=
IF
If ( d = log[b] a )
T(n) = n^d * (log n)
Master Theorem Case 3:
T(n)=
IF
If ( d < log[b] a )
T(n) = n^(log[b] a)
Using Master Method:
T(n) = 9T(n/3) + n
What are a, b, c, d?
What is Big-O?
a = 9 b = 3 c = 1 d = 1 Because d = 1 and log<3> 9 = 2 d < log<b> a T(n) = n^(log<b> a) => n^(log<3> 9) T(n) = n^2</b></b>
Using Master Method:
T(n) = T(2n/3) + 1
What are a, b, c, d?
What is Big-O?
a = 1 b=3/2 c= 1 d = 0
log<3/2> 1 = 0 and d = 0
d = log<b> a</b>
T(n) = n^0 * log n => 1 * log n T(n) = log n</b>
Using Master Method:
T(n) = 3T(n/4) + n*log n
What are a, b, c, d?
What is Big-O?
a = 3 b = 4 c= log n d = 1 log<b> a = log<4> 3 = x and 0 < x < 1 d > log<b> a 1 > x T(n) = c * n^d T(n) = n*log n</b></b>
Using Master Method:
T(n) = 2T(n/2) + n
What are a, b, c, d?
What is Big-O?
a = 2 b =2 c = 1 d = 1 log<2> 2 = 1 d= 1 log<b> a = d so T(n) = (n^1) log n T(n) = n log n</b>
Using Master Method:
T(n) = 8T(n/2) + n^2
What are a, b, c, d?
What is Big-O?
a = 8 b = 2 c = 1 d = 2 log<2> 8 = 3 d < log<b> a => 2 < 3 so T(n) = n^(log<b> a) T(n) = n^3</b></b>
List comparison sort algorithms:
Insertion Sort:
Merge Sort: A[n], B[m], C[n+m)
Heaps
Quick Sort
Which can have duplicate values? Heaps or Binary Search Trees?
Heaps
Last Child in a Heap is?
The LOWEST right child
Insertion Sort T(n) Best/Worst?
Best = T(n) = n -1
Worst: T(n) = n^2
Merge Sort T(n) Worst? Which variable are passed in?
Worst: W(n,m) = n+m-1 COMPARISONS
T(n) = nlog n - (n-1)
O(n) = nlog n
A[n], B[m], C[n+m)
Heaps Sort T(n) Worst? Build? Shrinking Cost? Insert/Increase Key? Return Max?
Worst Building Cost = O(n) Shrinking Cost = O(n log n) Worst = O(n log n) Priority Queue (Heap) functions Increase Key (or insert) O(n) = log n Return Max = O(n) = 1
Which comparison sorts are Worst O(n) = n log n?
Heaps and Merge Sort (and on average not worst case Quick Sort)
Which comparison sorts are Worst O(n) = n^2
Insertion Sort and Quick Sort
Quick sort is only n^2 if the list is sorting such that A[n] < A[n+1]
Mostly Quick sort is n log n
BST n = max number of nodes in a tree of given height h. What is the function for n? What is the function for h? What is the worst time complexity?
n = 2^h - 1 h = log (n+1) O(n) = log n