160 likes | 260 Vues
Thoughts. Most coding errors are/were small ones Test in isolation Question what you see – does it make sense. Analysis. 1,000,000 find + add/removes in ~ 50,000 item BST takes x time Find = log(n) Add or remove = log(n) Find+add or remove = O( logn ). 50000 = x. Analysis.
E N D
Thoughts • Most coding errors are/were small ones • Test in isolation • Question what you see – does it make sense
Analysis • 1,000,000 find + add/removes in ~50,000 item BST takes x time • Find = log(n) • Add or remove = log(n) • Find+add or remove = O(logn) 50000 = x
Analysis • Do same in sorted array list? • Find = O(logn) • Add or remove both O(n) • Find + add/remove = O(n) =
Analysis • Do same in sorted array list? • Find = O(logn) • Add or remove both O(n) • Find + add/remove = O(n) =
Analysis • Do same in sorted array list? = ~3200
Union • Set A has n items, set B has m items • Approach 1: • Empty set C • Walk through A, add each item to C • Walk through B, add each item to C
Union • Set A has n items, set B has m items • Approach 1: • Empty set C • Walk through A, add each item to C n steps each log(n) • Walk through B, add each item to C
Union • Set A has n items, set B has m items • Approach 1: • Empty set C • Walk through A, add each item to C n·log(n) • Walk through B, add each item to C
Union • Set A has n items, set B has m items • Approach 1: • Empty set C • Walk through A, add each item to C n·log(n) • Walk through B, add each item to C m steps each log(size(C))
Union • Set A has n items, set B has m items • Approach 1: • Empty set C • Walk through A, add each item to C n·log(n) • Walk through B, add each item to C m steps each log(n + m)
Union • Set A has n items, set B has m items • Approach 1: • Empty set C • Walk through A, add each item to C n·log(n) • Walk through B, add each item to Cm·log(n + m)
Union • Set A has n items, set B has m items • Approach 1: • Empty set C • Walk through A, add each item to C: n·log(n) • Walk through B, add each item to C: m·log(n + m) • O(nlogn) + O(m·log(n+m)) • Dominated by O(m·log(n+m)) unless m is tiny
Union • Set A has n items, set B has m items • Approach 2: • Copy A to C: O(n) • Walk through B, add each item to C
Union • Set A has n items, set B has m items • Approach 2: • Copy A to C: O(n) • Walk through B : m, add each item to C O(log(n+m))
Union • Set A has n items, set B has m items • Approach 2: • Copy A to C: O(n) • Walk through B : m, add each item to CO(log(n+m)) • O(n) + O(m·log(n+m)) • Dominated by O(m·log(n+m)) unless m is tiny
Optimal • Tree A -> Vector A' : O(n) time • Tree B -> Vector B' : O(n) time • Merge A' + B' into combined Vec C' : O(n + m) • Make BST from Vec C': • Recursively build tree using binary search in linear time : O(n + m) Total : O(n + m)