Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

45
Slide 1 of Lecture G - Collections Lecture G - Collections Unit G1 – Abstract Data Types
  • date post

    18-Dec-2015
  • Category

    Documents

  • view

    216
  • download

    1

Transcript of Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Page 1: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 1 of 45.Lecture G - Collections

Lecture G - Collections

Unit G1 – Abstract Data Types

Page 2: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 2 of 45.Lecture G - Collections

Collections

Array-based implementations of simple collection

abstract data types

Page 3: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 3 of 45.Lecture G - Collections

Collection data types

• Very often one creates objects that hold collections of items.

• Each type of collection has rules for accessing the elements in it Array: the items are indexed by integers, and each item can be

accessed according to its index Set: the items are un-ordered and appear at most once, and items

are accessed according to their value Map (dictionary, associative array): the items are indexed by keys,

and each item can be accessed according to its key Queue: the items are ordered and can be accessed only in FIFO

order (first in first out) Stack: the items are ordered and can be accessed only in LIFO

order (last in first out)

Page 4: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 4 of 45.Lecture G - Collections

Abstract data types

• Data types are defined abstractly: what operations they support.

• Each data type can be implemented in various different ways

• Each implementation has its own data structure• Implementations may differ in their efficiency for various

operations or in their storage requirements• This is the standard dichotomy of interface vs.

implementations• In this course we will only look at very simple

implementations of basic abstract data types

Page 5: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 5 of 45.Lecture G - Collections

The Set abstract data type

• A Set is an un-ordered collection of items with no duplicates allowed. It supports the following operations: Create an empty Set Add an item to the set Delete an item form the set Check whether an item is in the set

• We will exhibit an implementation using an array to hold the items

• Our solution will be for a set of integers • Generic solutions are also possible• This implementation is not efficient

Page 6: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 6 of 45.Lecture G - Collections

Set

public class Set { // The elements of this set, in no particular order private int[] elements; // The number of elements in this set private int size; private final DEFAULT_LENGTH = 100; public Set(int maxSize) { elements = new int[maxSize]; size=0; } public Set() { this(DEFAULT_LENGTH);}

Page 7: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 7 of 45.Lecture G - Collections

Set methods

public boolean contains (int x) { for(int j=0 ; j<size ; j++) if ( elements[j] == x) return true; return false; } public void insert(int x) { if ( !contains(x) ) elements[size++] = x; } public void delete(int x){ for(int j=0 ; j<size ; j++) if ( elements[j] == x) { elements[j] = elements[--size]; return; } }

Page 8: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 8 of 45.Lecture G - Collections

Set – resizing on overflow

public void safeInsert(int x) { if ( !contains(x) ) { if (size == elements.length) resize(); elements[size++] = x; } }

private void resize() { int[] temp = new int[2*elements.length]; for (int j=0 ; j<size ; j++) temp[j] = elements[j]; elements = temp; }

Page 9: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 9 of 45.Lecture G - Collections

Set – variants for union methods

public void insertSet(Set s) { for (int j= 0 ; j < s.size ; j++) insert(s.elements[j]); } public Set union(Set s} { Set u = new Set(size +s.size ); u.insertSet(this); u.insertSet(s); return u; } public static Set union(Set s, Set t) { return s.union(t); }

Page 10: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 10 of 45.Lecture G - Collections

Immutable Set

• An immutable object type is an object that can not be changed after its construction

• An immutable set does not support the insert and delete operations

• Instead, its constructor will receive an array of the elements in the set

• It only supports the contains predicate• We will show an efficient implementation for immutable

sets contains() will use binary search contains() will require only O(log N) time

Page 11: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 11 of 45.Lecture G - Collections

ImmutableSet

public class ImmutableSet { /** The elements of this set, ordered from lowest to * highest */ private int[] elements; /** The elements given as the parameter do not have * to be ordered. We do assume that there are no * duplicates. */ public ImmutableSet(int[] elements) { this.elements = new int[elements.length]; for(int j=0 ; j < elements.length;j++) this.elements[j]=elements[j]; MergeSort.mergeSort(this.elements); }

Page 12: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 12 of 45.Lecture G - Collections

ImmutableSet – binary search

public boolean contains (int x) { return contains(x, 0, elements.length - 1); } private boolean contains(int x, int low,

int high){ if (low > high) return false; int med = (low + high) / 2; if (x == elements[med]) return true; else if (x < elements[med]) return contains(x, low, med-1); else return contains(x, med+1, high); }

Page 13: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 13 of 45.Lecture G - Collections

Lecture G - Collections

Unit G2 - Stacks

Page 14: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 14 of 45.Lecture G - Collections

Stacks

How to use and implement stacks

Page 15: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 15 of 45.Lecture G - Collections

The Stack data type

• A stack holds an ordered collection of items, items can be accessed only in first-in-last-out order

• Its operations are: Create an empty stack Push an item into the stack Pop an item from the stack – removes (and returns) the last item

that was pushed onto the stack Check whether the stack it empty or not

• Used in many aspects of implementation of high level programming languages

• Most CPUs support stacks in hardware

Page 16: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 16 of 45.Lecture G - Collections

Stack sample run

• Create empty stack { }• Push 5 { 5 }• Push 4 { 5 4 }• Push 8 { 5 4 8 }• Pop (returns 8) { 5 4 }• Push 7 { 5 4 7 }• Pop (returns 7) { 5 4 }• Pop (returns 4) { 5 }

Page 17: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 17 of 45.Lecture G - Collections

Evaluating expressions

• 5 * (( 6 + 3) / ( 7 – 2 * 2)) Push 5 { 5 } Push 6 { 5 6 } Push 3 { 5 6 3 } + push( pop() + pop() ) { 5 9 } Push 7 { 5 9 7 } Push 4 { 5 9 7 2 } Push 1 { 5 9 7 2 2 } * push( pop() * pop() ) { 5 9 7 4 } - push( pop() - pop() ) { 5 9 3 } / push( pop() / pop() ) { 5 3 } * push( pop() * pop() ) { 15 }

Page 18: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 18 of 45.Lecture G - Collections

Handling return addresses

class A {

void a() {

// …

B.b()

// …

B.c()

// …

}

}

class B {

public void b() {

// …

c();

// …

}

public void c() {

// …

}

}

1

4

5A.a :

B.b : 2ret :A.a(1)

A.a :

B.b :

3B.c :

ret :A.a(1)

ret :B.b(2)

A.a :

B.c : 6ret : .a(5)

1

2

3

4

5

6

Page 19: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 19 of 45.Lecture G - Collections

Allocating parameters and local variables

void a() {

int x, y;

b(5);

c(6, 7);

}

void b(int z) {

int w;

c(8, 9);

}

void c(int q, int r) {

int s;

}

a : 1a : 1a :a :

2params :z=5

locals: wb :

a :a :

3

params :z=5

locals: wb :

params :q=8,r=9

locals:sc :

4

5

a :a :

6params :r=6,q=7

locals: sc :

1

2

3

4

5

6

Page 20: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 20 of 45.Lecture G - Collections

The Method Frame

void a() {

int x, y;

b(5);

}

void b(int z) {

int w;

w = 1 + 5 * c(8, 9);

}

int c(int q, int r) {

int s;

return 7 + q ;

}

1a : 1

a :

b : 2params :z=5

return : a(1)

locals: w

comp:w=1+5*c(8,9)

a :

3

b : params :z=5

return : a(1)

locals: w

comp:w=1+5*c(8,9)

params :q=8,r=9

return : b(2)

locals: s

comp:7+q

1

2

3

Page 21: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 21 of 45.Lecture G - Collections

Array based Stack implementation

• We will show an array based implementation We will ignore overflow – exceeding the array size

• Can be corrected using resize() We will ignore underflow – popping from an empty stack

• This is the caller’s error – should be an exception

• All methods run in O(1) time• Later we will show another implementation

Page 22: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 22 of 45.Lecture G - Collections

Stack

public class Stack { private int[] elements; private int top; private final static int DEFAULT_MAX_SIZE = 10;

public Stack(int maxSize){elements = new int[maxSize];top=0;}

public Stack() { this(DEFAULT_MAX_SIZE); }

public void push(int x) { elements[top++] =x; } public int pop() { return elements[--top]; }

public boolean isEmpty() { return top == 0; }}

Page 23: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 23 of 45.Lecture G - Collections

Lecture G - Collections

Unit G3 – Linked List structure

Page 24: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 24 of 45.Lecture G - Collections

Linked Data Structures

How to build and use recursive data

structures

Page 25: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 25 of 45.Lecture G - Collections

Recursive data structures

• An object may have fields of its own type• This does not create a problem since the field only has a

reference to the other object• This allows building complicated linked data structures

For each person, a set of friends For each house on a street, its two neighbors For each vertex in a binary tree, its two sons For each web page, the pages that it links to

• There are several common structures Lists (singly linked, doubly linked) Trees (binary, n-ary, search, …) Graphs (directed, undirected)

Page 26: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 26 of 45.Lecture G - Collections

Person

public class Person { private Person bestFriend; private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public Person getBestFriend() { return bestFriend; } public void setBestFriend(Person friend) { bestFriend = friend; }}

Page 27: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 27 of 45.Lecture G - Collections

Person Usage Example (add animation)

Person a = new person(“Alice”); Person b = new Person(“Bob”);Person c = new Person(“Carol”);Person d = new Person(“Danny”); a.setBestFriend(b);b.setBestFriend(a);c.setBestFriend(d);d.setbestFriend(a);Person e = c.getBestFriend().getBestFriend(); // a.

System.out.println(e.getName()); // Aliceif (e == b.getBestFriend()) { … } // true

e

CarolCarol

c

DannyDannyd

BobBobb

AliceAlicea

Page 28: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 28 of 45.Lecture G - Collections

Linked Lists

• The simplest linked data structure: a simple linear list.

datadata

data

data

null

start

Page 29: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 29 of 45.Lecture G - Collections

List

public class List { private int data; private List next; public List(int data, List next) { this.data = data; this.next = next; } public int getData() { return data; } public List getNext() { return next; }}

Page 30: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 30 of 45.Lecture G - Collections

Implementing a Set

public class Set { private List elements; public Set() { elements = null; } public boolean contains(int x) { for (List c = elements ; c != null ; c = c.getNext()) if (c.getData() == x) return true; return false; } public void insert(int x) { if (!contains(x)) elements = new List(x, elements); } }

Page 31: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 31 of 45.Lecture G - Collections

Sample run

Set s = new Set();s.insert(3);s.insert(5)if (s.contains(3)) { … }

1

2

3

nullelements

1

nullelements 3

2

nullelements 35

3

Page 32: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 32 of 45.Lecture G - Collections

Sample run

Set s = new Set();s.insert(3);s.insert(5)if (s.contains(3)) { … }

1

2

3

4

nullelements 35

4

c

if(c.getData()==3)

Page 33: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 33 of 45.Lecture G - Collections

Sample run

Set s = new Set();s.insert(3);s.insert(5)if (s.contains(3)) { … }

1

2

3

4

nullelements 35

4

c

if(c.getData()==3)

Page 34: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 34 of 45.Lecture G - Collections

List iterator

public class ListIterator { private List current;

public ListIterator(List list) { current = list; } public boolean hasNext() { return current != null; } public int nextItem() { int item = current.getData(); current = current.getNext(); return item; }}

Page 35: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 35 of 45.Lecture G - Collections

Using Iterators

public class Set { private List elements; // constructor and insert() as before public boolean contains(int x) { for (ListIterator l = new ListIterator(elements);l.hasNext();) if (l.nextItem() == x) return true; return false; } public String toString() { StringBuffer answer = new Stringbuffer(“{“); for (ListIterator l = new ListIterator(elements);l.hasNext();) answer.append(“ “ + l.nextItem() + “ “); answer.append(“}”); return answer.toString(); }}

Page 36: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 36 of 45.Lecture G - Collections

Implementing a Stackpublic class Stack { private List elements;

public Stack() { elements = null; } public void push(int x) { elements = new List(x, elements); } public boolean isEmpty() { return elements == null; } public int pop() { int x = elements.getData(); elements = elements.getNext(); return x; }}

Page 37: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 37 of 45.Lecture G - Collections

Lecture G4 - Collections

Unit G4 - List Represnetation of Naturals

Page 38: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 38 of 45.Lecture G - Collections

Recursion on lists

An example of using lists and recursion

for implementing the natural numbers

Page 39: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 39 of 45.Lecture G - Collections

Foundations of Logic and Computation

• What are the very basic axioms of mathematics? Usually the axioms of Zermello-Frenkel set theory Only sets exists in this theory How are natural numbers handled? Built recursively from sets: 0 = {} , 1 = { {} } , 2 = { {} { {} } } , …

• What is the simplest computer? Usually one takes the “Turing Machine” What can it do? Everything that any other computer can do How? It can simulate any other computer

Page 40: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 40 of 45.Lecture G - Collections

Successor representation of the naturals

• Mathematically, the only basic notions you need in order to define the natural numbers are 1 (the first natural) Successor (succ(x) = x + 1) Induction

• We will provide a Java representation of the naturals using the successor notion in a linked list Mathematical Operations will be defined using recursion

null

3:

Page 41: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 41 of 45.Lecture G - Collections

Naturalpublic class Natural { private Natural predecessor; public static final Natural ZERO = null; public Natural(Natural predecessor) { this.predecessor = predecessor; } public Natural minus1() { return predecessor; } public Natural plus1() { return new Natural(this); } public boolean equals1() { return predecessor == ZERO; }

Page 42: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 42 of 45.Lecture G - Collections

+ , - , =, > public Natural plus(Natural y) { if (y == ZERO) return this; return this.plus1().plus(y.minus1()); }

/** returns max(this-y, 0) */ public Natural minus(Natural y) { if (y == ZERO) return this; if (y.equals1()) return ZERO; return this.minus1().minus(y.minus1()); }

public boolean ge(Natural y) { return y.minus(this) == ZERO; }

public boolean eq(Natural y) {return this.ge(y) && y.ge(this);}

public boolean gt(Natural y) { return !y.ge(this); }

Page 43: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 43 of 45.Lecture G - Collections

*, / , mod public Natural times(Natural y) { if (y == ZERO) return ZERO; return this.plus(this.times(y.minus1())); }

public Natural div(Natural y) { if ( y.gt(this) ) return ZERO; return ((this.minus(y)).div(y)).plus1(); }

public Natural mod(Natural y) { return this.minus((this.div(y)).times(y)); }

Page 44: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 44 of 45.Lecture G - Collections

printing final static Natural ONE = new Natural(ZERO); final static Natural TEN= ONE.plus1().plus1().plus1().plus1(). plus1().plus1() .plus1().plus1().plus1();

private char lastDigit() { Natrual digit = this.mod(TEN); if ( digit == ZERO ) return ‘0’; if ( (digit = digit.minus1()) == ZERO ) return ‘1’; if ( (digit = digit.minus1()) == ZERO ) return ‘2’; // … if ( (digit = digit.minus1()) == ZERO ) return ‘8’; return ‘9’; } public String toString() { return (TEN.gt(this) ? “” : this.div(TEN).toString())

+lastDigit(); }}

Page 45: Slide 1 of 45. Lecture G - Collections Unit G1 – Abstract Data Types.

Slide 45 of 45.Lecture G - Collections

Lecture G - Collections