From 5b667ae6912559a326ef580a681cc805f556fcaf Mon Sep 17 00:00:00 2001 From: Louie S Date: Thu, 9 Apr 2020 11:44:54 -0700 Subject: Post-class 04/10 --- 04-08.md | 4 ++ 04-10.md | 176 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 180 insertions(+) create mode 100644 04-10.md diff --git a/04-08.md b/04-08.md index e4c4111..a39e9e5 100644 --- a/04-08.md +++ b/04-08.md @@ -180,3 +180,7 @@ for(i=1; i<=n; i++){ - x = (n-1)+(n-2)+...+2+1+0 - 2x = (n-1)\*n -> x = ((n-1)\*n)/2 - O(x) = O(((n-1)\*n)/2) -> O(n^2) + +--- + +[04/10 ->](04-10.md) diff --git a/04-10.md b/04-10.md new file mode 100644 index 0000000..379e952 --- /dev/null +++ b/04-10.md @@ -0,0 +1,176 @@ +[\<- 04/08](04-08.md) + +--- + +## Review - Data Structure + +What is a data structure? +- How data is organized in memory (or hard disk) + +Why do we care about data structure? +- Efficiency - time/space efficiency +- How to measure time efficiency? + - Count # of operations + - What types of operations do we care about? + - Insertion + - Deletion + - Access/Search + - Min/Max + - Union/Merge + - When do we care? + - We only care about the one with the highest impact on efficiency + +## Review - Big-O Notation + +The correct form of big-O +- Drop all but the fastest-growing term +- Drop the constant coefficient of the remaining term +- e.g `1500n^2 + 4n + 3log(n) + 2` -> `1500n^2` -> `n^2` + - Big-O notation for this example would be O(n^2) + +How to evaluate the big-O for a piece of code? +- We mainly care about repetitive operations + - Operations that are only executed once (or constant times) will be ignored +- Loops + - Single layer loop + - Nested loop + +## Summary: Big-O for Nested Loops + +Step 1: Analyze if it's a dependent loop or independent loop. Assume the counter variable of the outsider loop is `i` +1. if `i` is not involved in insider loop -> **independent loop** +2. Otherwise -> **dependent loop** + +Step 2: If independent loop: +- O_overall = O(outsider loop) * O(insider loop) +- Otherwise (dependent loop): + - For each iteration of the outsider loop -> count # of operations for the insider loop, add them together + +## Nested Loop II - Dependent Loops + +``` +for(i=0; i x = log3(n)+1 + - O(x) = O(log(n)) + +``` +for(i=0; i=1; i=i/3){ + for(j=0; j