Presentation is loading. Please wait.

Presentation is loading. Please wait.

22C:21 Problem 2 (Set 1) Solution outline.

Similar presentations


Presentation on theme: "22C:21 Problem 2 (Set 1) Solution outline."— Presentation transcript:

1 22C:21 Problem 2 (Set 1) Solution outline

2 Original INSERT code public void insert (Record rec) {
// Check for overflow if (numRecords == maxRecords) { return; // Doing nothing }

3 Modified INSERT code public void insert (Record rec) {
// Check for overflow. Double when necessary. if (numRecords == maxRecords) { maxRecords *= 2; Record tempList[] = new Record[maxRecords]; System.arraycopy(recordList,0,tempList,0,recordList.length); recordList = tempList; }

4 Output --------------------------- Capacity:2 0 3
Record inserted at position 0: 3 1 22 Record inserted at position 1: 22 Capacity:4 1 13 2 22 Record inserted at position 1: 13 (and so on)

5 Amortized Analysis Average running time per operation over a sequence of worst-case operations.

6 am·or·tize     [am-er-tahyz, uh-mawr-tahyz] –verb (used with object), -tized, -tiz·ing.
1.Finance. a. to liquidate or extinguish (a mortgage, debt, or other obligation), esp. by periodic payments to the creditor or to a sinking fund. b. to write off a cost of (an asset) gradually. 2.Old English Law. to convey to a corporation or church group; alienate in mortmain.

7 Basic idea Knowledge of which sequence of operations is possible.
Data structures that have states that persists between operations. Worst-case operation can alter the state in a way that worst-case doesn’t occur again for a long time. Thus amortizing the cost!

8 Some intuition … so on Now t = 4, Total cost $2t = $8

9 Formal analysis Consider DynamicRecordDB with N slots and n records.
INSERT operations doubles the size before adding another item if n = N. Any operation that doesn’t involve doubling takes O(1) time unit – say, at most 1 seconds. Resizing takes 2n seconds.

10 Analysis (contd.) We start from empty list and perform i INSERT operations. So, n = i and N is the smallest power of 2 ≥ i. Total seconds for all the resizing operations = … +N/4 + N/2 + N = 2N – 2. In reference to the code: n = numRecords, N = maxRecords. We start with N = 2. Then N becomes 4 and finally 8.

11 Analysis (almost done!)
Total seconds for i INSERTs = i + 2N – 2 Now, N ≤ 2n = 2i. So the i INSERTs take O(5i – 2) or O(i) time. This is worst case! So, on average, each INSERT takes O(i)/i = O(1) time. This is the amortized running time of insertion.

12 Bottom line(s) Amortized analysis is a way of proving that even if an operation is occasionally expensive, its cost is made up for by other, cheaper occurrences of the same operation.


Download ppt "22C:21 Problem 2 (Set 1) Solution outline."

Similar presentations


Ads by Google