22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department http://www.cs.uiowa.edu/~hzhang/c31/



Similar documents
\Mankinds's progress is measured by the number of. Elementary data structures such as stacks, queues,

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Sequential Data Structures

Big O and Limits Abstract Data Types Data Structure Grand Tour.

Universidad Carlos III de Madrid

LINKED DATA STRUCTURES

Introduction to Data Structures

Linked Lists Linked Lists, Queues, and Stacks

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Introduction to Data Structures and Algorithms

Analysis of a Search Algorithm

PES Institute of Technology-BSC QUESTION BANK

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Common Data Structures

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

10CS35: Data Structures Using C

Lecture 2: Data Structures Steven Skiena. skiena

Chapter 3: Restricted Structures Page 1

Module 2 Stacks and Queues: Abstract Data Types

St S a t ck a ck nd Qu Q eue 1

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Algorithms and Data Structures

DATA STRUCTURE - STACK

Data Structures Using C++ 2E. Chapter 5 Linked Lists

STACKS,QUEUES, AND LINKED LISTS

DATA STRUCTURE - QUEUE

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

DATA STRUCTURES USING C

Data Structures and Algorithms Stacks and Queues

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Cpt S 223. School of EECS, WSU

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

7.1 Our Current Model

Data Structure [Question Bank]

Stacks. Data Structures and Data Types. Collections

D06 PROGRAMMING with JAVA

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Data Structures in the Java API

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Analysis of Algorithms I: Binary Search Trees

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Building Java Programs

Programming with Data Structures

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Binary Heap Algorithms

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

Abstract Data Types. Chapter 2

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Algorithms and Data Structures

Cpt S 223. School of EECS, WSU

ADTs,, Arrays, Linked Lists

Introduction to Programming System Design. CSCI 455x (4 Units)

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

Data Structures and Algorithms Lists

The Java Collections Framework

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Node-Based Structures Linked Lists: Implementation

CmpSci 187: Programming with Data Structures Spring 2015

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Data Structures and Data Manipulation

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

recursion, O(n), linked lists 6/14

Data Structures and Algorithms

Building Java Programs

Chapter 8: Bags and Sets

CompSci-61B, Data Structures Final Exam

6 March Array Implementation of Binary Trees

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

AP Computer Science AB Syllabus 1

Lecture 12 Doubly Linked Lists (with Recursion)

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Stacks. Linear data structures

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Algorithms. Margaret M. Fleck. 18 October 2010

Data Structures. Chapter 8

Algorithms and Data Structures

Transcription:

22c:31 Algorithms Ch3: Data Structures Hantao Zhang Computer Science Department http://www.cs.uiowa.edu/~hzhang/c31/

Linear Data Structures Now we can now explore some convenient techniques for organizing and managing information Topics: collections Abstract Data Types (ADTs) dynamic structures and linked lists queues and stacks 1

Collections A collection is an object that serves as a repository for other objects A collection usually provides services such as adding, removing, and otherwise managing the elements it contains Sometimes the elements in a collection are ordered, sometimes they are not Sometimes collections are homogeneous, sometimes the are heterogeneous 2

Abstract Data Types Collections can be implemented in many different ways An abstract data type (ADT) is an organized collection of information and a set of operations used to manage that information The set of operations defines the interface to the ADT As long as the ADT fulfills the promises of the interface, it doesn't really matter how the ADT is implemented Objects are a perfect programming mechanism to create ADTs because their internal details are encapsulated 3

Abstraction Our data structures should be abstractions, so they can be reused to save cost That is, they should hide unneeded details We want to separate the interface of the structure from its underlying implementation This helps manage complexity and makes it possible to change the implementation without changing the interface 4

Collection Classes The Java standard library contains several classes that represent collections, often referred to as the Java Collections API Their underlying implementation is implied in the class names such as ArrayList and LinkedList ArrayList is an implementation of List based on arrays. LinedList is an implementation of List based on nodes. Many abstract data types can be implemented based on List, such as, Set, Map, Stack, and Queue 5

Generics Classes The Java Collection classes are implemented as generic types We give the type of object a collection will hold when we create the collection, like this: ArrayList<String> mystringlist = new ArrayList<String>(); List<Book> mybooklist = new ArrayList<Book>(); 6 If no type is given, the collection is defined as containing references to the Object class

Example Uses of ArrayList import java.util.*; // before define a class ArrayList<String> mystringlist = new ArrayList<String>(); mystringlist.add("item"); //add an item at the end of list mystringlist.add(new Integer(2)); //compilation error int size = mystringlist.size(); // return the size of the list int index = stringlist.indexof( ABC"); //location of object ABC in List for (int i = 0; i < mystringlist.size(); i++) String item = mystringlist.get(i); System.out.println("Item " + i + " : " + item);} System.out.println( All Items: " + mystringlist); 7

Example Uses of ArrayList (cont.) if (mystringlist.contains( ABC ) == true) System.out.println( the list has Item ABC ); mystringlist.remove(0); // remove the first item from the list mystringlist.remove( ABC ); // remove the first copy of item ABC from the list // copy list into another list ArrayList<String> copyofstringlist = new ArrayList<String>(); copyofstringlist.addall(mystringlist); mystringlist.set(0,"item2"); // replace the first item by item Item2 // converting from ArrayList to Array String[] itemarray = new String[myStringList.size()]; mystringlist.toarray(itemarray); 8

9 Example Uses of LinkedList import java.util.*; public class LinkedListDemo { public static void main(string args[]) { // create a linked list LinkedList<String> mylist = new LinkedList<String>(); // add elements to the linked list mylist.add("f"); mylist.add("b"); mylist.add("d"); mylist.add("e"); mylist.add("c"); mylist.addlast("z"); mylist.addfirst("a"); mylist.add(1, "A2"); System.out.println("Original contents of mylist: " + mylist); // remove elements from the linked list mylist.remove("f"); mylist.remove(2); System.out.println("Contents of mylist after deletion: " + mylist); // remove first and last elements mylist.removefirst(); mylist.removelast(); System.out.println("myList after deleting first and last: " + mylist); } }

Example Uses of LinkedList Output of the previous program: Original contents of mylist: [A, A2, F, B, D, E, C, Z] Contents of mylist after deletion: [A, A2, D, E, C, Z] mylist after deleting first and last: [A2, D, E, C] 10

Static vs. Dynamic Structures A static data structure has a fixed size This meaning is different from the meaning of the static modifier in java Arrays are static; once you define the number of elements it can hold, the number doesn t change A dynamic data structure grows and shrinks at execution time as required by its contents A dynamic data structure is implemented using links Is ArrayList dynamic or not? 11

Arrays An array is a structure of fixed-size data records such that each element can be efficiently located by its index or (equivalently) address. Advantages of contiguously-allocated arrays include: Constant-time access given the index. Arrays consist purely of data, so no space is wasted with links or other formatting information. Physical continuity (memory locality) between successive data accesses helps exploit the high-speed cache memory on modern computer architectures.

Dynamic Arrays Unfortunately we cannot adjust the size of simple arrays in the middle of a program s execution. Compensating by allocating extremely large arrays can waste a lot of space. With dynamic arrays we start with an array of size 1, and double its size from m to 2m each time we run out of space. How many times will we double for n elements? Only log 2 n.

How Much Total Work? The apparent waste in this procedure involves the recopying of the old contents on each expansion. If half the elements move once, a quarter of the elements twice, and so on, the total number of movements M is given by M = lg n i i=1 n/2i = n lg n i=1 i/2i n i=1 i/2i = 2n Thus each of the n elements move an average of only twice, and the total work of managing the dynamic array is the same O(n) as a simple array.

Object References Recall that an object reference is a variable that stores the address of an object A reference also can be called a pointer References often are depicted graphically: student John Smith 40725 3.58 12

References as Links Object references can be used to create links between objects Suppose a Student class contains a reference to another Student object John Smith 40725 3.57 Jane Jones 58821 3.72 13

References as Links References can be used to create a variety of linked structures, such as a linked list: studentlist 14

Intermediate Nodes The objects being stored should not be concerned with the details of the data structure in which they may be stored For example, the Student class should not have to store a link to the next Student object in the list Instead, we can use a separate node class with two parts: 1) a reference to an independent object and 2) a link to the next node in the list The internal representation becomes a linked list of nodes 15

Inserting a Node A method called insert could be defined to add a node anywhere in the list, to keep it sorted, for example Inserting at the front of a linked list is a special case 16

Inserting a Node When inserting a node in the middle of a linked list, we must first find the spot to insert it Let current refer to the node before the spot where the new node will be inserted 17

Deleting a Node A method called delete could be defined to remove a node from the list Again the front of the list is a special case: Deleting from the middle of the list: 18

Other Dynamic List Representations It may be convenient to implement as list as a doubly linked list, with next and previous references list 19

Other Dynamic List Implementations It may be convenient to use a separate header node, with a count and references to both the front and rear of the list list count: 4 front rear 20

Other Dynamic List Implementations A linked list can be circularly linked in which case the last node in the list points to the first node in the list If the linked list is doubly linked, the first node in the list also points to the last node in the list The representation should facilitate the intended operations and should make them easy to implement 21

Queues A queue is similar to a list but adds items only to the rear of the list and removes them only from the front It is called a FIFO data structure: First-In, First- Out enqueue dequeue Analogy: a line of people at a bank teller s window 22

Queues We can define the operations for a queue enqueue - add an item to the rear of the queue dequeue (or serve) - remove an item from the front of the queue isempty - returns true if the queue is empty Queues often are helpful in simulations or any situation in which items get backed up while awaiting processing Java provides a Queue interface, which the LinkedList class implements: Queue<String> q = new LinkedList<String>(); 23

Stacks A stack ADT is also linear, like a list or a queue Items are added and removed from only one end of a stack It is therefore LIFO: Last-In, First-Out Analogies: a stack of plates in a cupboard, a stack of bills to be paid, or a stack of hay bales in a barn 24

Stacks Stacks often are drawn vertically: push pop 25

Stacks Some stack operations: push - add an item to the top of the stack pop - remove an item from the top of the stack peek - retrieves the top item without removing it isempty - returns true if the stack is empty A stack can be represented by a singly-linked list; it doesn t matter whether the references point from the top toward the bottom or vice versa A stack can be represented by an array 26

Stacks The Stack class is part of the Java Collections API and thus is a generic class Stack<String> strstack = new Stack<String>(); 27

Dictonary / Dynamic Set Operations Perhaps the most important class of data structures maintain a set of items, indexed by keys. Search(S,k) A query that, given a set S and a key value k, returns a pointer x to an element in S such that key[x] = k, or nil if no such element belongs to S. Insert(S,x) A modifying operation that augments the set S with the element x. Delete(S,x) Given a pointer x to an element in the set S, remove x from S. Observe we are given a pointer to an element x, not a key value.

Min(S), Max(S) Returns the element of the totally ordered set S which has the smallest (largest) key. Next(S,x), Previous(S,x) Given an element x whose key is from a totally ordered set S, returns the next largest (smallest) element in S, or NIL if x is the maximum (minimum) element. There are a variety of implementations of these dictionary operations, each of which yield different time bounds for various operations.

Array Based Sets: Unsorted Arrays Search(S,k) - sequential search, O(n) Insert(S,x) - place in first empty spot, O(1) Delete(S,x) - copy nth item to the xth spot, O(1) Min(S,x), Max(S,x) - sequential search, O(n) Successor(S,x), Predecessor(S,x) - sequential search, O(n)

Array Based Sets: Sorted Arrays Search(S,k) - binary search, O(lg n) Insert(S,x) - search, then move to make space, O(n) Delete(S,x) - move to fill up the hole, O(n) Min(S,x), Max(S,x) - first or last element, O(1) Successor(S,x), Predecessor(S,x) - Add or subtract 1 from pointer, O(1)

Problem of the Day What is the asymptotic worst-case running times for each of the seven fundamental dictionary operations when the data structure is implemented as A singly-linked unsorted list, A doubly-linked unsorted list, A singly-linked sorted list, and finally A doubly-linked sorted list.

Solution Blank Search(L, k) Insert(L, x) Delete(L, x) Successor(L, x) Predecessor(L, x) Minimum(L) Maximum(L) singly singly doubly doubly unsorted sorted unsorted sorted

Solution singly double singly doubly Dictionary operation unsorted unsorted sorted sorted Search(L, k) O(n) O(n) O(n) O(n) Insert(L, x) O(1) O(1) O(n) O(n) Delete(L, x) O(n) O(1) O(n) O(1) Successor(L, x) O(n) O(n) O(1) O(1) Predecessor(L, x) O(n) O(n) O(n) O(1) Minimum(L) O(n) O(n) O(1) O(1) Maximum(L) O(n) O(n) O(1) O(1)