Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Algorithm Design (Review). Java basics Object-oriented design Stacks, queues, and deques Vectors, lists and sequences Trees and binary.

Similar presentations


Presentation on theme: "Data Structures and Algorithm Design (Review). Java basics Object-oriented design Stacks, queues, and deques Vectors, lists and sequences Trees and binary."— Presentation transcript:

1 Data Structures and Algorithm Design (Review)

2 Java basics Object-oriented design Stacks, queues, and deques Vectors, lists and sequences Trees and binary trees Data Structures and Algorithm Design: …

3 Java Basics Class Class Modifiers abstract, final, public Variable Modifiers public, protected, private, static, final Methods Method Modifiers public, protected, private, abstract, final, static Arrays int[] a = new int[ 10 ]; float[][] x = new float[ 8 ][ 10 ]; a[ i ] = 138; x[ i ][ i + 1 ] = 2.189 + x[ i ][ i ];

4 Java Basics Recursion public class RecursionExample { public static int function(int n) { if (n==0) return 1; if (n==1) return 1; if (n==2) return 3; else return 3*function(n-3) + 4*function(n-2) + 5*function(n-1); } public static void main(String []args){ int num = Integer.parseInt(args[0]); System.out.println(num); int b = function(num); System.out.println("f =" + " " + b); }}

5 Object-Oriented Design Inheritance Polymorphism method overriding method overloading Keyword: this Exception Interface, Abstract Classes Type casting

6 import java.util.*; import java.lang.*; interface CanFight { void fight ( );} interface CanSwim { void swim ( );} interface CanFly {void fly ( );} class ActionCharacter { public void fight( ) { }} class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { public void fight ( ) {System.out.println(“Can fight!”);} public void swim ( ) {System.out.println(“Can swim!”); } public void fly ( ) {System.out.println(“Can fly!”);} }

7 public class Adventure { static void t(CanFight x) { x.fight();} static void u(CanSwim x) { x.swim();} static void v(CanFly x) { x.fly();} static void w(ActionCharacter x) { x.fight();} public static void main (String[ ] args) { Hero h = new Hero( ); t(h); //Treat it as a CanFight u(h); //Treat it as a CanSwim v(h); //Treat it as a CanFly w(h); //Treat it as an ActionCharacter }

8 HeroActionCharacterCanFightCanSwimCanFly subclassimplementation h instantiation Hero h = new Hero( ) t(h); //Treat it as a CanFight u(h); //Treat it as a CanSwim v(h); //Treat it as a CanFly w(h); //Treat it as an ActionCharacter static void t(CanFight x) { x.fight();} static void u(CanSwim x) { x.swim();} static void v(CanFly x) { x.fly();} static void w(ActionCharacter x) { x.fight();}

9 Stacks, Queues, and Deques Stacks Queues Deques Singly linked lists Doubly linked lists Sample case study application

10 Stacks Definition: A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. A stack S is an abstract data type (ADT) that supports following two fundamental methods: push(o): Insert object o at the top of the stack Input : Object; Output : None. pop(): Remove from the stack and return the top object on the stack; an error occurs if the stack is empty. Input : None; Output : Object

11 public interface Stack { public void push( Object element ); public Object pop() throws StackEmptyException; public int size(); public boolean isEmpty(); public Object top() throws StackEmptyException; }

12 public class ArrayStack implements Stack { public static final int CAPACITY = 1000; private in capacity; private Object [] S; private int top = -1; public ArrayStatck() { this( CAPACITY ); } public ArrayStack( int cap ) { capacity = cap; S = new Object[ capacity ]; } public int size() { return ( top + 1 ); }

13 public boolean isEmpty() { return( top < 0 ); } public void push( Object obj ) throws StackFullException { if( size() == capacity ) throw new StackFullException( "Stack overflow" ); S[ ++top ] = obj; } public Object top() throws StackEmptyException { if( isEmpty() ) throw new StackEmptyException( "Stack is empty." ); return S[ top ]; }

14 public Object pop() throws StackEmptyException { Object elem; if( isEmpty() ) throw new StackEmptyException( "Stack is Empty." ); elem = S[ top ]; S[ top-- ] = null; return elem; }

15 Sample Case Study Application We want to write a program to calculate the span of the stock’s price on a given day. The span of the stock’s price on a given day: The maximum number of the consecutive days up to the current day such that the stock price on each of those days has been less than or equal to the price on the current day.

16 Java Implementation

17 Main idea: The span s i on a certain day i can be easily computed if we know the closest day preceding day i, such that the price on that day is higher than the price on day i. If such a preceding day exists for a day i, let us denote it with h(i), and otherwise let us define h(i) = -1. Then, s i = i – h(i).

18 h(0) h(1) 0 h(2) 1 h(3) 1 h(4) 3 h(5) 1 h(6) 0 s i = i – h(i). s0s0 1 s1s1 1 s2s2 1 s3s3 2 s4s4 1 s5s5 4 s6s6 6

19 The problem is how to compute h(i) efficiently? Step 1: p 0 = 48.97. h(0) = -1, s 0 = 0 - h(0) = 0 – (-1) = 1 0 Day 0. It is possible that h(1) = 0. Step 2: p 1 = 47.54. Pop days with prices less than or equal to p 1. At this point of time, we have only one element in the stack. It is 0 and p 0 > p 1. So h(1) = 0, s 1 = 1 - h(1) = 1 – 0 = 1. Day 1. It is possible that h(2) = 1. 0 1

20 Step 3: p 2 = 45.83. Pop days with prices less than or equal to p 2. At this point of time, we have two elements in the stack. The top one is 1 and p 1 > p 2. So h(2) = 1, s 2 = 2 - h(2) = 2 – 1 = 1. Day 2. It is possible that h(3) = 2. 1 2 0 Step 4: p 3 = 46.34. Pop days with prices less than or equal to p 3. The top one will be taken out since p 3 > p 2. The second one is 1 and p 1 > p 3. So h(3) = 1, s 3 = 3 - h(3) = 3 – 1 = 2. Day 3. It is possible that h(4) = 3. 0 1 3

21 Step 5: p 4 = 45.68. Pop days with prices less than or equal to p 4. The top one is 3 and p 3 > p 4. So h(4) = 3, s 4 = 4 - h(3) = 4 – 3 = 1. Day 4. It is possible that h(5) = 4. 0 1 3 4 Step 6: p 5 = 46.95. Pop days with prices less than or equal to p 3. The top two will be taken out since p 5 > p 4 and p 5 > p 3. The third one is 1 and p 1 > p 5. So h(5) = 1, s 5 = 5 - h(5) = 5 – 1 = 4. Day 5. It is possible that h(6) = 5. 0 1 5

22 Step 7: p 6 = 48.17. Pop days with prices less than or equal to p 3. The top two will be taken out since p 6 > p 5 and p 6 > p 1. The third one is 0 and p 0 > p 6. So h(6) = 0, s 5 = 6 - h(6) = 6 – 0 = 6. Day 6. The price on day 6. The process stops. 0 6

23 How to calculate 1+2-3+4-5+6+7-8+9? public class ExpressionAlculation { public static void main(String [] args){ String s = "1+2-3+4-5+6+7-8+9"; char c = 0; int result = 0; Object temp; Stack myStack = new ArrayStack(); myStack.push(new Integer(1)); for (int i = 1; i < s.length(); i++){ if (s.charAt(i) == ‘+’ || s.charAt(i) == ‘-’) myStack.push(new Character(s.charAt(i))); else {temp = myStack.pop(); result = ((Integer)myStack.pop()).intValue(); c = s.charAt(i); if (temp == ‘+’) result = result + (c-'0'); else result = result - (c-'0'); myStack.push(new Integer(result));} } System.out.println("Total is " + result); }

24 Queues Definition: A queue is a container of objects that are inserted and removed according to the first-in first-out (FIFO) principle.

25

26 class ArrayQueue implements Queue { private Object[] elem; private int front, rear; private static final int DEFAULT_LENGTH = 100; private int length; public ArrayQueue() { this(DEFAULT_LENGTH); } public ArrayQueue(int length) { elem = new Object[length]; front = rear = 0; this.length = length; }

27 public void enqueue(Object element) throws QueueFullException { if (size()==length-1) throw new QueueFullException(); else { elem[rear] = element; rear = (rear+1)%length; }

28 public Object dequeue() throws QueueEmptyException {if (isEmpty()) throw new QueueEmptyException(); else {Object temp = elem[front]; elem[front] = null; front = (front+1)%length; return temp; } private boolean isFull() { return (rear-front)==(length-1); }

29 public int size() { return (length-front+rear)%length; } public boolean isEmpty() { return front==rear; } public Object front() throws QueueEmptyException { if (isEmpty()) throw new QueueEmptyException(); else return elem[front]; }

30 Queues Application: Search a tree in the breadth-first-manner enqueue(root); while (the queue is not empty) do {x := dequeue; print(x); let x 1, x 2, …, x k be the children of x; for (i = k to 1) do {enqueue(x i );} }

31 Queues Sample trace: 1 step1: 2323 step2: visit(1) 345345 step3: visit(2) 45674567 step4: visit(3) 5678956789 step5: visit(4) 678 91011 step6: visit(5) …

32 Singly Linked Lists

33 Class Node

34

35 Node x = new Node(); x.setElement(new String(“Baltimore”));

36 x.setNext(head); head = x;

37 head = head.getNext();

38 How to generate a singly linked list? public class Head_and_Tail { Node head; Node tail; Head_and_Tail(Node x, Node y) { head = x; tail = y; }

39 public class GeneratingList { Node head = null; Node tail = null; Public Head_and_Tail linked_list () { Node x = null; for (int i = 0; i < 10; i++) {x = new Node(); x.setElement(new Integer(i)); if (i == 0 ) {x.setNext(null); tail = x;} else x.setNext(head); head = x; } return new Head_and_Tail(head, tail);} }

40 Doubly Linked List Difference from singly linked lists: -each node contains two links. -two extra nodes: header and trailer, which contain no elements.

41 Class DLNode

42

43 DLNode x = new DLNode(); x.setElement(new String(“Toronto”)); (x.element  new String(“Toronto”)) Have a new node: header RomeSeattle trailer Baltimore Toronto

44 x.setPrev(header); x.setNext(header.getNext()); (header.getNext()).setPrev(x); header.setNext(x); x.prev  header; x.next  header.next; header.next.prev  x; header.next  x; Update the links: header RomeSeattle trailer Baltimore Toronto

45 ((trailer.getPrev()).getPrev).setNext(trailer); trailer.setPrev((trailer.getPrev()).getPrev()); trailer.prev.prev.next  trailer; trailer.prev  trailer.prev.prev; Update the links: header Rome Seattle trailer BaltimoreToronto

46 Deques Definition: A double-ended queue is a queue that supports insertion and deletion at both the front and the rear of the queue. A deque D is an abstract data type that supports the following four fundamental methods:

47 public interface Deque { void insertFirst(Object e); void insertLast(Object e); Object removeFirst(); Object removeLast(); Object first(); Object last(); int size(); boolean isEmpty(); }

48 Class MyDeque

49 Implementing Stacks and Queues with Deques

50

51 Class DequeStack

52

53 Vectors, Lists, and Sequences Vectors Lists Sequences Iterators

54 Vector (interface)List (interface) Sequence (interface)ArrayVector (class)NodeList (class) ArraySequence (class)NodeSequence (class) impl. extends impl. extends

55 public interface Vector { public int size(); public boolean isEmpty(); public Object elemAtRank(int r); public Object replaceAtRank(int r, Object e); public void insertAtRank(int r, Object e); public Object removeAtRank(int r); } Vectors

56 public class ArrayVector implements Vector { private Object[] A;// array storing the elements of the vector private int capacity = 16;// initial length of array A private int size = 0;// number of elements stored in the vector /** Creates the vector with initial capacity 16. */ public ArrayVector() { A = new Object[capacity]; }

57 public Object elemAtRank(int r) {return a[r];} public int size() {return size;} public boolean isEmpty {return size()==0;} public Object replaceAtRank (int r, Object e) { Object temp=a[r]; a[r]=e; return temp; }

58 /** Inserts an element at the given rank. */ public void insertAtRank(int r, Object e) throws BoundaryViolationException { checkRank(r, size() + 1); if (size == capacity) {// an overflow capacity *= 2; Object[] B = new Object[capacity]; for (int i=0; i<size; i++) B[i] = A[i]; A = B;} for (int i=size-1; i>=r; i--)// shift elements up A[i+1] = A[i]; A[r] = e; size++; }

59 /** Removes the element stored at the given rank. */ public Object removeAtRank(int r) throws BoundaryViolationException { checkRank(r, size()); Object temp = A[r]; for (int i=r; i<size-1; i++)// shift elements down A[i] = A[i+1]; size--; return temp; } public int size( ) {return size;}

60 public interface Position { Object element(); } Lists

61

62

63 Position element(); Dnode element(){…}; getNext(){…}; getPrev(){…}; setNext(){…}; setPrev(){…}; setElement(){…}; impl.

64 public interface List { /** Returns the number of elements in this list. */ public int size(); /** Returns whether the list is empty. */ public boolean isEmpty(); /** Returns the first node in the list. */ public Position first(); /** Returns the last node in the list. */ public Position last(); /** Returns the node after a given node in the list. */ public Position next(Position p) throws InvalidPositionException, BoundaryViolationException; /** Returns the node before a given node in the list. */ public Position prev(Position p) throws InvalidPositionException, BoundaryViolationException;

65 /** Inserts an element at the front of the list. */ public Position insertFirst(Object e); /** Inserts and element at the back of the list. */ public Position insertLast(Object e); /** Inserts an element after the given node in the list. */ public Position insertAfter(Position p, Object e) throws InvalidPositionException; /** Inserts an element before the given node in the list. */ public Position insertBefore(Position p, Object e) throws InvalidPositionException; /** Removes a node from the list. */ public Object remove(Position p) throws InvalidPositionException; /** Replaces the element stored at the given node. */ public Object replace(Position p, Object e) throws InvalidPositionException; }

66 Class NodeList

67

68

69

70

71

72

73

74 List first(); last(); isFirst(); isLast(); before(); after(); replaceElement(); swapElement(); insertFirst(); insertLast(); NodeList … …. impl.

75 Sequence

76

77 Sequence ADT Positionrank Doubly linked list NodeatRank(r) rankOf(p) Implementation of a sequence with a doubly linked list:

78 /** Implementation of a sequence by means of a doubly linked list. */ public class NodeSequence extends NodeList implements Sequence { /** Checks whether the given rank is in the range [0, n - 1] */ protected void checkRank(int r, int n) throws BoundaryViolationException { if (r = n) throw new BoundaryViolationException("Illegal rank: " + r); }

79 /** Returns the position containing the element at the given rank; * O(n) time. */ public Position atRank (int rank) { DNode node; checkRank(rank, size()); if (rank <= size()/2) { // scan forward from the head node = header.getNext(); for (int i=0; i < rank; i++) node = node.getNext(); } else { // scan backward from the tail node = trailer.getPrev(); for (int i=1; i < size()-rank; i++) node = node.getPrev();} return node; }

80 /** Gets an element at the given rank.*/ public Object elemAtRank(int r) { return atRank(r).element(); } /** Returns the rank of a given position.*/ public int rankOf(Position p) { DNode node; node = header.getNext(); for for (int i=1; i < size(); i++) { if (p == node) return i; else node = node.getNext();} }

81 /** Inserts an element at the given rank; O(n) time. */ public void insertAtRank (int rank, Object element) throws BoundaryViolationException { checkRank(rank, size() + 1); if (rank == size()) insertLast(element); else { insertBefore(atRank(rank), element); }

82 /** Removes the element stored at the given rank; O(n) time. */ public Object removeAtRank (int rank) throws BoundaryViolationException { checkRank(rank, size()); return remove(atRank(rank)); } public Object replaceAtRank (int rank, object element) throws BoundadryViolationException { checkRank(rank); return replaceElement(atRank(rank), element); }

83 Implementing a Sequence with an Array

84 Iterator

85

86 An implementation of the Iterator is always related to container, i.e., a vector, a list, or a sequence. The following is an exemplary implementation of the List Iterator. public class PositionIterator implements Iterator { protected List list; // the underlying list protected Position cur; // the current (next) position public PositionIterator() { } // default constructor public PositionIterator(List L) { // preferred constructor list = L; if (list.isEmpty()) cur = null; // list is empty else cur = list.first(); // start with the first position }

87 public boolean hasNext() { return (cur != null); } public Object next() throws NoSuchElementException { if (!hasNext()) throw new NoSuchElementException("No next position"); Position toReturn = cur; if (cur == list.last()) cur = null; // no positions left else cur = list.next(cur); // move cursor to the next position return toReturn; } class NoSuchElementException extends Exception { public NoSuchElementException() {super();} public NoSuchElementException(String s) { super(s); } }

88 In a similar way, we can establish an ElementIterator as follows. public class ElementIterator implements Iterator { protected List list; // the underlying list protected Position cur; // the current (next) position protected Object elementCur;// the current (next) element public ElementIterator() { } // default constructor public ElementIterator(List L) { // preferred constructor list = L; if (list.isEmpty()) cur = null; // list is empty else cur = list.first(); // start with the first position }

89 public boolean hasNext() { return (cur != null); } public Object next() throws NoSuchElementException { if (!hasNext()) throw new NoSuchElementException("No next position"); elementCur = cur.element(); if (cur == list.last()) cur = null; // no positions left else cur = list.next(cur); // move cursor to the next position return elementCur; }

90

91 Trees What is a tree? Tree ADT Basic algorithms on trees Tree traversal

92 What is a tree?

93 public interface Tree { public int size(); public Boolean isEmpty(); public ElementIterator elements(); public PositionIterator positions(); public void swapElements( Position v, Position w ); public Object replaceElement( Position v, Object e ); public Position root(); public Position parent( Position v ); public PositionIterator children( Position v ); public boolean isInternal( Position v ); public boolean isExternal( Position v ); public boolean isRoot( Position v ); } Tree Interface – Tree ADT

94 IspectableContainer size isElement Elements IspectablePositionContainer positions PositionContainer swapElement replaceElement InspectableTree root parent children isRoot isInternal isExternal Tree

95 A Binary Tree Interface in Java

96

97

98

99

100

101 Class BTNode

102 Interface Hierarchy for Positions Position element(); DNode element(){…}; getNext(){…}; getPrev(){…}; setNext(){…}; setPrev(){…}; setElement(){…}; BTNnode element(){…}; getLeft(){…}; getRight(){…}; setLeft(){…}; setRight(){…}; getParent(){…} setElement(){…};

103 Also see the complete program for “LinkedBinaryTree” posted on the home page of Dr. Yangjun Chen.

104 IspectableContainer size isElement Elements IspectablePositionContainer positions PositionContainer swapElement replaceElement InspectableTree root, parent, children, isRoot isInternal, isExternal Tree InspectableBinaryTree leftChild, rightChild, sibling BinaryTree LinkedBinaryTree … …, replaceElement, swapElement, expandExternal, removeAboveExternal imple.

105 Basic Algorithms on Trees

106

107 Inorder tree traversal

108 inorder(T, r) if … inorder(T, u) “visit” r If … inorder (T, a) inorder(T, u) if … inorder(T, w) “visit” u If … inorder (T, v) inorder(T, w) if … “visit” w if … 1 26

109 inorder(T, x) if … “visit” x if … 3 inorder(T, v) if … inorder(T, x) “visit” v If … inorder (T, y) 4

110 if … “visit” y if … 5 inorder(T, a) if … inorder(T, b) “visit” a If … inorder (T, c) 8 7 9

111 Inorder traversal based on Stack data structure Algorithm Stack-control-inorder(T, v) establish stack S; S.push(v); while (S is not empty) do {u := S.pop(); if u is leaf or u is marked, visit u; else {let v1 and v2 be the left and right child node of v, respectively; S.push(v2); mark u; S.push(u*); S.push(v1); }

112 u r* a r w u* v r* a u* v r* a print(w) v r* a print(u) x v* y r* a v* y r* a print(x) y r* a print(v) r* a print(y) a print(r) b a* c a* c print(b) c print(a)print(c)


Download ppt "Data Structures and Algorithm Design (Review). Java basics Object-oriented design Stacks, queues, and deques Vectors, lists and sequences Trees and binary."

Similar presentations


Ads by Google