Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Algorithm Design (Review).

Similar presentations


Presentation on theme: "Data Structures and Algorithm Design (Review)."— Presentation transcript:

1 Data Structures and Algorithm Design (Review)

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

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 ] = 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 Stacks, Queues, and Deques
Singly linked lists Doubly linked lists Sample case study application

7 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 s tack 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. : None; : Object

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

9 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 );

10 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 ];

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

12 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.

13 Java Implementation

14 Main idea: The span si 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, si = i – h(i).

15 si = i – h(i). h(0) -1 h(1) h(2) 1 h(3) 1 h(4) 3 h(5) 1 h(6) s0 s1 s2 s3 s4 s5 s6 1 1 1 2 1 4 6

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

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

18 p4 = 45.68. Pop days with prices less than or equal to p4.
Step 5: p4 = Pop days with prices less than or equal to p4. The top one is 3 and p3 > p4. So h(4) = 3, s4 = 4 - h(3) = 4 – 3 = 1. Day 4. It is possible that h(5) = 4. 4 3 1 Step 6: p5 = Pop days with prices less than or equal to p3. The top two will be taken out since p5 > p4 and p5 > p3. The third one is 1 and p1 > p5. So h(5) = 1, s5 = 5 - h(5) = 5 – 1 = 4. Day 5. It is possible that h(6) = 5. 1 5

19 p6 = 48.17. Pop days with prices less than or equal to p3.
Step 7: p6 = Pop days with prices less than or equal to p3. The top two will be taken out since p6 > p5 and p6 > p1. The third one is 0 and p0 > p6. So h(6) = 0, s5 = 6 - h(6) = 6 – 0 = 6. Day 6. The price on day 6. The process stops. 6

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

21

22 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;

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

24 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);

25 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];

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

27 Queues Sample trace: 1 step1: 2 5 step2: visit(1) 5 3 4 step3:
2 5 step2: visit(1) 5 3 4 step3: visit(2) step4: visit(5) step5: visit(3) 6 7 8 step6: visit(4) 7 8 step7: visit(6) 8 step8: visit(7) empty step9: visit(8)

28 Singly Linked Lists

29 Class Node

30

31 How to generate a singly linked list?
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.element = new Integer(i); if (i == 0 ) {x.next = null; tail = x;} else x.next = head; head = x; } return new Head-and-Tail(head, tail);}

32 public class Head-and-Tail {
Node head; Node tail; Head-and-Tail(Node x, Node y) { head = x; tail = y; }

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

34 Class DLNode

35

36 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:

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

38 Class MyDeque

39 Vectors, Lists, and Sequences
Iterators

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

41 Vectors 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); }

42 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]; }

43 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; }

44 /** 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++; }

45 /** 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;}

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

47

48

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

50 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)

51 /** 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) /** 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) }

52 Class NodeList

53

54

55

56

57

58

59

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

61 Sequence

62

63 Implementation of a sequence with a doubly linked list:
Sequence ADT Position rank Node atRank(r) rankOf(p) Doubly linked list

64 /** 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 < 0 || r >= n) throw new BoundaryViolationException("Illegal rank: " + r); }

65 /** 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; }

66 /** 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();}

67 /** 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); }

68 /** 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);

69 Implementing a Sequence with an Array

70 Iterator

71

72 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 }

73 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); }

74 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 }

75 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; }

76

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

78 What is a tree?

79 Tree Interface – Tree ADT
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 ); }

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

81 A Binary Tree Interface in Java

82

83

84

85

86

87 Class BTNode

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

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

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

91 Basic Algorithms on Trees

92

93 Inorder tree traversal

94 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 … 1 6 2 “visit” w if …

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

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

97 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); }

98 r u r* a w u* v r* a u* v r* a v r* a print(u) print(w) 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)

99 How to calculate 1+2+3+4-5+6+7-8+9?
public class ExpressionAlculation { public static void main(String [] args){ String s = " "; 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);


Download ppt "Data Structures and Algorithm Design (Review)."

Similar presentations


Ads by Google