CS261 Data Structures Dynamic Arrays. Pro: only core data structure designed to hold a collection of elements Pro: random access: can quickly get to any.

Slides:



Advertisements
Similar presentations
Stacks using Linked Lists. Stack Data Structure As we already know, stacks are linear data structures. This means that their contexts are stored in what.
Advertisements

Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
CS 473Lecture X1 CS473-Algorithms I Lecture X Dynamic Tables.
Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
ArrayLists David Kauchak cs201 Spring Extendable array Arrays store data in sequential locations in memory Elements are accessed via their index.
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Today’s Agenda  Stacks  Queues  Priority Queues CS2336: Computer Science II.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CS 261- Winter 2009 Dynamic Array Queue and Deque.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Data Structures Hash Tables
CPSC 411, Fall 2008: Set 6 1 CPSC 411 Design and Analysis of Algorithms Set 6: Amortized Analysis Prof. Jennifer Welch Fall 2008.
Tirgul 9 Amortized analysis Graph representation.
CS 261 – Data Structures Priority Queues & Heaps.
CMPT 225 ADT List using Dynamic arrays A dynamic data structure is one that changes size, as needed, as items are inserted or removed The Java ArrayList.
CS305/503, Spring 2009 Amortized Analysis Michael Barnathan.
CS 307 Fundamentals of Computer Science 1 Lists and ArrayList many slides taken from Mike Scott, UT Austin.
CS 261 Winter 2010 Dynamic Array Introduction (aka Vector, ArrayList)
CS333 / Cutler Amortized Analysis 1 Amortized Analysis The average cost of a sequence of n operations on a given Data Structure. Aggregate Analysis Accounting.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Andreas Klappenecker [based on the slides of Prof. Welch]
Hashing General idea: Get a large array
Stacks, Queues, and Deques
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Stacks, Queues, and Deques
Data Structures — Lists and Trees CS-2301, B-Term Data Structures — Lists and Trees CS-2301, System Programming for Non-Majors (Slides include materials.
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
CS261 Data Structures Dynamic Arrays Part 2: Implementation.
Stacks - 2 Nour El-Kadri ITI Implementing 2 stacks in one array and we don’t mean two stacks growing in the same direction: but two stacks growing.
Recursion, Complexity, and Sorting By Andrew Zeng.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Amortized Analysis The problem domains vary widely, so this approach is not tied to any single data structure The goal is to guarantee the average performance.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Lists. Container Classes Many applications in Computer Science require the storage of information for collections of entities e.g. a student registration.
27/05/ Iteration Loops Nested Loops & The Step Parameter.
B-Trees. Motivation for B-Trees So far we have assumed that we can store an entire data structure in main memory What if we have so much data that it.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Amortized Algorithm Analysis COP3503 July 25, 2007 Andy Schwartz.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Advanced Algorithm Design and Analysis (Lecture 12) SW5 fall 2004 Simonas Šaltenis E1-215b
Tirgul 11 Notes Hash tables –reminder –examples –some new material.
CSCE 411H Design and Analysis of Algorithms Set 6: Amortized Analysis Prof. Evdokia Nikolova* Spring 2013 CSCE 411H, Spring 2013: Set 6 1 * Slides adapted.
CMSC 341 Amortized Analysis.
David Luebke 1 12/12/2015 CS 332: Algorithms Amortized Analysis.
CS 261 Fall 2009 Dynamic Array Introduction (aka Vector, ArrayList)
Question of the Day  How can you change the position of 1 toothpick and leave the giraffe in exactly the same form, but possibly mirror-imaged or oriented.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
1 Chapter 6 Methods for Making Data Structures. 2 Dynamic Arrays in Data Structures In almost every data structure, we want functions for inserting and.
ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: ec2620m.htm Office: TEL 3049.
Amortized Analysis In amortized analysis, the time required to perform a sequence of operations is averaged over all the operations performed Aggregate.
Amortized Analysis and Heaps Intro David Kauchak cs302 Spring 2013.
MA/CSSE 473 Day 12 Amortization (growable Array) Knuth interview Brute Force Examples.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Introduction to Algorithms: Amortized Analysis. Introduction to Algorithms Amortized Analysis Dynamic tables Aggregate method Accounting method Potential.
An Array-Based Implementation of the ADT List
Review Array Array Elements Accessing array elements
Andreas Klappenecker [partially based on the slides of Prof. Welch]
Lecture 16 Amortized Analysis
Tim Ehrlich Growing Arrays in C.
Data Structures Unsorted Arrays
Data Structures & Algorithms
Amortized Analysis and Heaps Intro
Arrays.
Linked List Intro CSCE 121.
B-Trees.
The Step Parameter & Nested For … To … Next loops
Dynamic Array: Implementation of Stack
Presentation transcript:

CS261 Data Structures Dynamic Arrays

Pro: only core data structure designed to hold a collection of elements Pro: random access: can quickly get to any element  O(1) Con: fixed size: – Maximum number of elements must be specified when created Arrays: Pros and Cons

The dynamic array (called Vector or ArrayList in Java, same thing, different API) gets around this by encapsulating a partially filled array that can grow when filled Hide memory management details behind a simple API Is still randomly accessible, but now it grows as necessary Dynamic Array (Vector or ArrayList)

Unlike arrays, a dynamic array can change its capacity Size is logical collection size: – Current number of elements in the dynamic array – What the programmer thinks of as the size of the collection – Managed by an internal data value Capacity is physical array size: # of elements it can hold before it must resize Size and Capacity

data Size = 6Capacity= 10 “Unused” elements

Capacity ( = cap ) Size ( = size ) 10 size = data = 16 cap = Partially Filled Dynamic Array

Adding an element to end is usually easy — just put new value at end and increment the (logical) size What happens when size reaches capacity? Adding an element

8 size = data = 8 cap = Before reallocation: Must allocate new (larger) array and copy valid data elements Also...don’t forget to free up the old array After reallocation: Set Capacity: Reallocate and Copy (animation) How much bigger should we make it?

Adding an element to middle can also force reallocation (if the current size is equal to capacity) But will ALWAYS require that elements be moved to make space – Our partially filled array should not have gaps so that we always know where the next element should go Adding to anywhere other than end is therefore O(n) worst case Adding to Middle

Must make space for new value Be Careful! Loop from bottom up while copying data BeforeAfter idx  Adding to Middle (cont.) Add at idx

Removing an element will also require “sliding over” to delete the value – We want to maintain a contiguous chunk of data so we always know where the next element goes and can put it there quickly! Therefore is O(n) worst case Removing an Element

Remove also requires a loop This time, should it be from top (e.g. at idx) or bottom? BeforeAfter idx  Remove Element Remove idx

Side Note realloc() can be used in place of malloc() to do resizing and *may* avoid ‘copying’ elements if possible – It’s still O(n) when it fails to enlarge the current array! For this class, use malloc only (so you’ll have to copy elements on a resize)

Something to think about… In the long term, are there any potential problems with the dynamic array? – hint: imagine adding MANY elements in the long term and potentially removing many of them.

Amortized Analysis What’s the cost of adding an element to the end of the array? Here?

Amortized Analysis To analyze an algorithm in which the worst case only occurs seldomly, we must perform an amortized analysis to get the average performance We’ll use the Accounting or Banker’s Method

Banker’s Method Assign a cost c’ i to each operation] When you perform the operation, if the actual cost c i, is less, then we save the credit c’ i – c i to hand out to future operations Otherwise, if the actual cost is more than the assigned cost, we borrow from the saved balance For n operations, the sum of the total assigned costs must be >= sum of actual costs

Example – Adding to Dynamic Array Add Element Old Capacity New Capacity Copy Count c’ i cici bibi (3-1) = (1+1) = 2(5-2) = (2+1) = 3(6-3) = (6-1) = (4+1) = 5(8-5) = (6-1) = (8-1) = (10-1) = (8+1) = 9(12-9) = (6-1) = 5 We say the add() operation is therefore O(1 + ) – amortized constant cost! c i = actual cost = insert (1) + copy cost (1) b i = bank account i =bankaccount i-1 + current deposit - actual cost = (b i-1 + c’ i ) - c i b i = bank account i =bankaccount i-1 + current deposit - actual cost = (b i-1 + c’ i ) - c i

Why do we bank a cost of 3 ? a b c a b c d e f 1 for the initial insert of each of d,e,f 1 for the copy upon resize to copy themselves a b c d e f And 1 to copy the other n/2 that were already in there!

Why do we bank a cost of 3 ? 1: to assign each of the new n/2 elements into the array 1: to copy the other n/2 that were already in the array Imagine you’re starting with a partially filled array of size n. It already has n/2 elements in it. For each element you add we’ll put a cost of 3 in the bank N 1: to copy each of the new n/2 elements into a larger array when it’s time to resize