Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exam #2 Review. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3.

Similar presentations


Presentation on theme: "Exam #2 Review. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3."— Presentation transcript:

1 Exam #2 Review

2 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 2 Evolution of Reusability, Genericity  Major theme in development of programming languages  Reuse code  Avoid repeatedly reinventing the wheel  Trend contributing to this  Use of generic code  Can be used with different types of data

3 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 3 Function Genericity Overloading and Templates  Initially code was reusable by encapsulating it within functions  Example lines of code to swap values stored in two variables  Instead of rewriting those 3 lines  Place in a function void swap (int & first, int & second) { int temp = first; first = second; second = temp; }  Then call swap(x,y);

4 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 4 Template Mechanism  Declare a type parameter  also called a type placeholder  Use it in the function instead of a specific type.  This requires a different kind of parameter list: void Swap(______ & first, ______ & second) { ________ temp = first; first = second; second = temp; }

5 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 5 Instantiating Class Templates  Instantiate it by using declaration of form ClassName object;  Passes Type as an argument to the class template definition.  Examples: Stack intSt; Stack stringSt;  Compiler will generate two distinct definitions of Stack  two instances  one for ints and one for strings.

6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 6 STL (Standard Template Library)  A library of class and function templates Components: 1. Containers : Generic "off-the-shelf" class templates for storing collections of data 2. Algorithms : Generic "off-the-shelf" function templates for operating on containers 3. Iterators : Generalized "smart" pointers that allow algorithms to operate on almost any container

7 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 7 The vector Container  A type-independent pattern for an array class  capacity can expand  self contained  Declaration template class vector {... } ;

8 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 8 vector Operations  Information about a vector's contents  v.size()  v.empty()  v.capacity()  v.reserve()  Adding, removing, accessing elements  v.push_back()  v.pop_back()  v.front()  v.back()

9 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 9 Increasing Capacity of a Vector  When vector v becomes full  capacity increased automatically when item added  Algorithm to increase capacity of vector  Allocate new array to store vector 's elements  use T copy constructor to copy existing elements to new array  Store item being added in new array  Destroy old array in vector  Make new array the vector 's storage array

10 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 10 Iterators  Each STL container declares an iterator type  can be used to define iterator objects  Iterators are a generalization of pointers that allow a C++ program to work with different data structures (containers) in a uniform manner  To declare an iterator object  the identifier iterator must be preceded by  name of container  scope operator ::  Example: vector ::iterator vecIter = v.begin()  Would define vecIter as an iterator positioned at the first element of v

11 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 11 Iterators Contrast use of subscript vs. use of iterator ostream & operator & v) { for (int i = 0; i < v.size(); i++) out << v[i] << " "; return out; } for (vector ::iterator it = v.begin(); it != v.end(); it++) out << *it << " ";

12 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 12 Iterator Functions  Note Table 9-5  Note the capability of the last two groupings  Possible to insert, erase elements of a vector anywhere in the vector  Must use iterators to do this  Note also these operations are as inefficient as for arrays due to the shifting required

13 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 13 Contrast Vectors and Arrays VectorsArrays Capacity can increase A self contained object Is a class template (No specific type) Has function members to do tasks Fixed size, cannot be changed during execution Cannot "operate" on itself Bound to specific type Must "re-invent the wheel" for most actions

14 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 14 STL's deque Class Template  Has the same operations as vector except …  there is no capacity() and no reserve()  Has two new operations:  d.push_front(value); Push copy of value at front of d  d.pop_front(value); Remove value at the front of d

15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 15 vector vs. deque vectordeque Capacity of a vector must be increased It must copy the objects from the old vector to the new vector It must destroy each object in the old vector A lot of overhead! With deque this copying, creating, and destroying is avoided. Once an object is constructed, it can stay in the same memory locations as long as it exists – If insertions and deletions take place at the ends of the deque.

16 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 16 vector vs. deque  Unlike vector s, a deque isn't stored in a single varying-sized block of memory, but rather in a collection of fixed-size blocks (typically, 4K bytes).  One of its data members is essentially an array map whose elements point to the locations of these blocks.

17 Linear Search Vector based search function template void LinearSearch (const vector &v, const t &item, boolean &found, int &loc) { found = false; loc = 0; while(loc < n && !found) { if (found || loc == v.size()) return; if (item == x[loc]) found = true; else loc++;} Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 17

18 Binary Search Binary search function for vector template void LinearSearch (const vector &v, const t &item, boolean &found, int &loc) { found = false; int first = 0; int last = v.size() - 1; while(first <= last && !found) { if (found || first > last) return; loc = (first + last) / 2; if (item < v[loc]) last = loc + 1; else if (item > v[loc]) first = loc + 1; else /* item == v[loc] */ found = true; } } Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 18

19 Binary Search  Usually outperforms a linear search  Disadvantage:  Requires a sequential storage  Not appropriate for linked lists (Why?)  It is possible to use a linked structure which can be searched in a binary-like manner Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 19

20 Trees  Tree terminology Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 20 Root node Leaf nodes Children of the parent (3) Siblings to each other Children of the parent (3) Siblings to each other

21 Binary Trees  Each node has at most two children  Useful in modeling processes where  a comparison or experiment has exactly two possible outcomes  the test is performed repeatedly  Example  multiple coin tosses  encoding/decoding messages in dots and dashes such as Morse code Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 21

22 Binary Trees  Each node has at most two children  Useful in modeling processes where  a comparison or experiment has exactly two possible outcomes  the test is performed repeatedly  Example  multiple coin tosses  encoding/decoding messages in dots and dashes such as Morse code Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 22

23 Array Representation of Binary Trees  Works OK for complete trees, not for sparse trees Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 23

24 Linked Representation of Binary Trees  Uses space more efficiently  Provides additional flexibility  Each node has two links  one to the left child of the node  one to the right child of the node  if no child node exists for a node, the link is set to NULL Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 24

25 Binary Trees as Recursive Data Structures  A binary tree is either empty … or  Consists of  a node called the root  root has pointers to two disjoint binary (sub)trees called …  right (sub)tree  left (sub)tree Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 25 Anchor Inductive step Which is either empty … or …

26 ADT Binary Search Tree (BST)  Collection of Data Elements  binary tree  each node x,  value in left child of x value in x in right child of x  Basic operations  Construct an empty BST  Determine if BST is empty  Search BST for given item Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 26

27 ADT Binary Search Tree (BST)  Basic operations (ctd)  Insert a new item in the BST  Maintain the BST property  Delete an item from the BST  Maintain the BST property  Traverse the BST  Visit each node exactly once  The inorder traversal must visit the values in the nodes in ascending order Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 27 View BST class template, Fig. 12-1 View BST class template, Fig. 12-1

28 BST Traversals  Note that recursive calls must be made  To left subtree  To right subtree  Must use two functions  Public method to send message to BST object Public method  Private auxiliary method that can access BinNodes and pointers within these nodes Private auxiliary method  Similar solution to graphic output  Public graphic method Public graphic method  Private graphAux method Private graphAux method Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 28

29 BST Searches  Search begins at root  If that is desired item, done  If item is less, move down left subtree  If item searched for is greater, move down right subtree  If item is not found, we will run into an empty subtree  View search() search() Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 29

30 Inserting into a BST  Insert function  Uses modified version of search to locate insertion location or already existing item  Pointer parent trails search pointer locptr, keeps track of parent node  Thus new node can be attached to BST in proper place  View insert() function insert() Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 30 R

31 Recursive Deletion Three possible cases to delete a node, x, from a BST 1. The node, x, is a leaf Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 31

32 Recursive Deletion 2. The node, x has one child Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 32

33 Recursive Deletion  x has two children Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 33 Replace contents of x with inorder successor K Delete node pointed to by xSucc as described for cases 1 and 2

34 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 34 Problem of Lopsidedness  Trees can be totally lopsided  Suppose each node has a right child only  Degenerates into a linked list Processing time affected by "shape" of tree

35 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 35 Hash Tables  In some situations faster search is needed  Solution is to use a hash function  Value of key field given to hash function  Location in a hash table is calculated

36 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 36 Hash Functions  Simple function could be to mod the value of the key by the size of the table  H(x) = x % tableSize  Note that we have traded speed for wasted space  Table must be considerably larger than number of items anticipated  Suggested to be 1.5-2x larger

37 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 37 Hash Functions  Observe the problem with same value returned by h(x) for different values of x  Called collisions  A simple solution is linear probing  Empty slots marked with -1  Linear search begins at collision location  Continues until empty slot found for insertion

38 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 38 Hash Functions  When retrieving a value linear probe until found  If empty slot encountered then value is not in table  If deletions permitted  Slot can be marked so it will not be empty and cause an invalid linear probe  Ex. -1 for unused slots, -2 for slots which used to contain data

39 Collision Reduction Strategies  Hash table capacity  Size of table must be 1.5 to 2 times the size of the number of items to be stored  Otherwise probability of collisions is too high Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 39

40 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 40 Collision Reduction Strategies  Linear probing can result in primary clustering  Consider quadratic probing  Probe sequence from location i is i + 1, i – 1, i + 4, i – 4, i + 9, i – 9, …  Secondary clusters can still form  Double hashing  Use a second hash function to determine probe sequence

41 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 41 Collision Reduction Strategies  Chaining  Table is a list or vector of head nodes to linked lists  When item hashes to location, it is added to that linked list

42 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 42 Improving the Hash Function  Ideal hash function  Simple to evaluate  Scatters items uniformly throughout table  Modulo arithmetic not so good for strings  Possible to manipulate numeric (ASCII) value of first and last characters of a name

43 43 Categories of Sorting Algorithms  Selection sort  Make passes through a list  On each pass reposition correctly some element (largest or smallest)

44 Array Based Selection Sort Pseudo- Code //x[0] is reserved For i = 1 to n-1 do the following: //Find the smallest element in the sublist x[i]…x[n] Set smallPos = i and smallest = x[smallPos] For j = i + 1 to n-1 do the following: If x[j] < smallest: //smaller element found Set smallPos = j and smallest = x[smallPos] End for //No interchange smallest with x[i], first element of this sublist. Set x[smallPos] = x[i] and x[i] = smallest End for Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 44

45 In-Class Exercise #1: Selection Sort  List of 9 elements: 90, 10, 80, 70, 20, 30, 50, 40, 60 Illustrate each pass… Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 45

46 Selection Sort Solution Pass 0901080702030504060 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 46 1109080702030504060 2102080709030504060 3102030709080504060 4102030409080507060 5102030405080907060 6102030405060907080 7102030405060709080 8102030405060708090

47 47 Categories of Sorting Algorithms  Exchange sort  Systematically interchange pairs of elements which are out of order  Bubble sort does this Out of order, exchange In order, do not exchange

48 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 48 Bubble Sort Algorithm 1. Initialize numCompares to n - 1 2. While numCompares != 0, do following a. Set last = 1 // location of last element in a swap b. For i = 1 to numPairs if x i > x i + 1 Swap x i and x i + 1 and set last = i c. Set numCompares = last – 1 End while

49 In-Class Exercise #2: Bubble Sort  List of 9 elements: 90, 10, 80, 70, 20, 30, 50, 40, 60 Illustrate each pass… Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 49

50 Bubble Sort Solution Pass 0901080702030504060 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 50 1108070203050406090 2107020305040608090 3102030504060708090 4102030405060708090 5102030405060708090

51 51 Categories of Sorting Algorithms  Insertion sort  Repeatedly insert a new element into an already sorted list  Note this works well with a linked list implementation All these have computing time O(n 2 )

52 Insertion Sort Pseduo Code (Instructor’s Recommendation) for j = 2 to A.length key = A[j] //Insert A[j] into the sorted sequence A[1..j-1] i = j-1 while i > 0 and A[i] > key A[i+1] = A[i] i = i-1 A[i+1] = key Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 52

53 Insertion Sort Example Pass 0524613 1254613 2245613 3245613 4124563 5123456 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 53

54 In-Class Exercise #3: Insertion Sort  List of 5 elements: 9, 3, 1, 5, 2 Illustrate each pass, along with algorithm values of key, j and i… Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 54

55 Insertion Sort Solution Pass 093152keyji 139152321,0 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 55 213952132,1,0 313592543,2 412359254,3,2,1

56 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 56 Quicksort  A more efficient exchange sorting scheme than bubble sort  A typical exchange involves elements that are far apart  Fewer interchanges are required to correctly position an element.  Quicksort uses a divide-and-conquer strategy  A recursive approach  The original problem partitioned into simpler sub- problems,  Each sub problem considered independently.  Subdivision continues until sub problems obtained are simple enough to be solved directly

57 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 57 Quicksort  Choose some element called a pivot  Perform a sequence of exchanges so that  All elements that are less than this pivot are to its left and  All elements that are greater than the pivot are to its right.  Divides the (sub)list into two smaller sub lists,  Each of which may then be sorted independently in the same way.

58 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 58 Quicksort If the list has 0 or 1 elements, return. // the list is sorted Else do: Pick an element in the list to use as the pivot. Split the remaining elements into two disjoint groups: SmallerThanPivot = {all elements < pivot} LargerThanPivot = {all elements > pivot} Return the list rearranged as: Quicksort(SmallerThanPivot), pivot, Quicksort(LargerThanPivot).

59 In-Class Exercise #4: Quicksort  List of 9 elements  30,10, 80, 70, 20, 90, 50, 40, 60  Pivot is the first element  Illustrate each pass  Clearly denote each sublist Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 59

60 Quicksort Solution Pass 0301080702090504060 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 60 1201030708090504060 2102030506040709080 3102030405060708090 TO DO: How does this change if you choose the pivot as the median?

61 A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level (nodes in left most positions) 2. The key in any node dominates the keys of its children  Min-heap: Node dominates by containing a smaller key than its children  Max-heap: Node dominates by containing a larger key than its children 61 Heaps

62 62 Implementing a Heap  Use an array or vector  Number the nodes from top to bottom  Number nodes on each row from left to right  Store data in i th node in i th location of array (vector)

63 63 Implementing a Heap  In an array implementation children of i th node are at myArray[2*i] and myArray[2*i+1]  Parent of the i th node is at myArray[i/2]

64 64 Basic Heap Operations  Construct an empty heap  Check if the heap is empty  Insert an item  Retrieve the largest/smallest element  Remove the largest/smallest element

65 65 Basic Heap Operations  Insert an item  Place new item at end of array  “Bubble” it up to the correct place  Interchange with parent so long as it is greater/less than its parent

66 66 Basic Heap Operations  Delete max/min item  Max/Min item is the root, swap with last node in tree  Delete last element  Bubble the top element down until heap property satisfied  Interchange with larger of two children

67 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 67

68 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 68 Percolate Down Algorithm 1. Set c = 2 * r 2. While r <= n do following a. If c < n and myArray[c] < myArray[c + 1] Increment c by 1 b. If myArray[r] < myArray[c] i. Swap myArray[r] and myArray[c] ii. set r = c iii. Set c = 2 * c else Terminate repetition End while

69 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 69 Heapsort  Given a list of numbers in an array  Stored in a complete binary tree  Convert to a heap  Begin at last node not a leaf  Apply percolated down to this subtree  Continue

70 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 70 Heapsort Algorithm 1. Consider x as a complete binary tree, use heapify to convert this tree to a heap 2. for i = n down to 2 : a. Interchange x[1] and x[i] (puts largest element at end) b. Apply percolate_down to convert binary tree corresponding to sublist in x[1].. x[i-1]

71 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 71 Heapsort  Now swap element 1 (root of tree) with last element  This puts largest element in correct location  Use percolate down on remaining sublist  Converts from semi-heap to heap

72 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 72 Heapsort  Now swap element 1 (root of tree) with last element  This puts largest element in correct location  Use percolate down on remaining sublist  Converts from semi-heap to heap

73 In-Class Exercise #4: Heapsort  For each step, want to draw the heap and array  30, 10, 80, 70, 20, 90, 40 Array? Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 73 1234567 30108070209040

74 Step 1: Convert to a heap  Begin at the last node that is not a leaf, apply the percolate down procedure to convert to a heap the subtree rooted at this node, move to the preceding node and percolat down in that subtree and so on, working our way up the tree, until we reach the root of the given tree. (HEAPIFY) Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 74

75 Step 1 (ctd)  What is the last node that is not a leaf?  Apply percolate down Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 75 1234567 30109070208040

76 Step 1 (ctd) Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 76 1234567 30709010208040

77 Step 1(ctd) Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 77 1234567 90708010203040 We now have a heap!

78 Step 2: Sort and Swap  The largest element is now at the root  Correctly position the largest element by swapping it with the element at the end of the list and go back and sort the remaining 6 elements Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 78 1234567 90708010203040 1234567 708010203090

79 Step 2 (ctd)  This is not a heap. However, since only the root changed, it is a semi- heap  Use percolate down to convert to a heap Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 79

80 Step 2 (ctd) Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 80 1234567 704010203090 1. Swap 2. Prune 1234567 30704010208090

81 Continue the pattern Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 81 1234567 70304010208090 1234567 20304010708090

82 Continue the pattern Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 82 1234567 40302010708090 1234567 10302040708090

83 Continue the pattern Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 83 1234567 30102040708090 1234567 20103040708090

84 Complete! Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 84 1234567 20103040708090 1234567 10203040708090

85 85 Sorting Facts  Sorting schemes are either …  internal -- designed for data items stored in main memory  external -- designed for data items stored in secondary memory. (Disk Drive)  Previous sorting schemes were all internal sorting algorithms:  required direct access to list elements  not possible for sequential files  made many passes through the list  not practical for files

86 86 Mergesort  Mergesort can be used both as an internal and an external sort.  A divide and conquer algorithm  Basic operation in mergesort is merging,  combining two lists that have previously been sorted  resulting list is also sorted.

87 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 87 Merge Algorithm 1. Open File1 and File2 for input, File3 for output 2. Read first element x from File1 and first element y from File2 3. While neither eof File1 or eof File2 If x < y then a. Write x to File3 b. Read a new x value from File1 Otherwise a. Write y to File3 b. Read a new y from File2 End while 4. If eof File1 encountered copy rest of of File2 into File3. If eof File2 encountered, copy rest of File1 into File3

88 88 Mergesort Algorithm

89 In-Class Exercise #6  Take File1 and File2 and produce a sorted File 3 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 89 File 1 79193347518299 File 2 1118244961 File 3

90 Mergesort Solution Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 90 File 179193347518299 File 2 1118244961 File 3 7 9 11 18 19 24 33 47 49 51 61 82 99

91 Fun Facts  Most of the time spent in merging  Combining two sorted lists of size n/2  What is the runtime of merge()?  Does not sort in-place  Requires extra memory to do the merging  Then copied back into the original memory  Good for external sorting  Disks are slow  Writing in long streams is more efficient 91 O(n)

92 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 92 Binary Merge Sort  Given a single file  Split into two files

93 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 93 Binary Merge Sort  Merge first one-element "subfile" of F1 with first one-element subfile of F2  Gives a sorted two-element subfile of F  Continue with rest of one-element subfiles

94 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 94 Binary Merge Sort  Split again  Merge again as before  Each time, the size of the sorted subgroups doubles

95 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 95 Binary Merge Sort  Last splitting gives two files each in order  Last merging yields a single file, entirely in order Note we always are limited to subfiles of some power of 2

96 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 96 Natural Merge Sort  Allows sorted subfiles of other sizes  Number of phases can be reduced when file contains longer "runs" of ordered elements  Consider file to be sorted, note in order groups

97 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 97 Natural Merge Sort  Copy alternate groupings into two files  Use the sub-groupings, not a power of 2  Look for possible larger groupings

98 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 98 Natural Merge Sort  Merge the corresponding sub files EOF for F2, Copy remaining groups from F1

99 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 99 Natural Merge Sort  Split again, alternating groups  Merge again, now two subgroups  One more split, one more merge gives sort


Download ppt "Exam #2 Review. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3."

Similar presentations


Ads by Google