Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All.

Slides:



Advertisements
Similar presentations
Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
Advertisements

AVL Trees1 Part-F2 AVL Trees v z. AVL Trees2 AVL Tree Definition (§ 9.2) AVL trees are balanced. An AVL Tree is a binary search tree such that.
Transform and Conquer Chapter 6. Transform and Conquer Solve problem by transforming into: a more convenient instance of the same problem (instance simplification)
Chapter 4: Divide and Conquer Master Theorem, Mergesort, Quicksort, Binary Search, Binary Trees The Design and Analysis of Algorithms.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 24 Sorting.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Sorting Gordon College 13.1 Some O(n2) Sorting Schemes
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Sorting.
Section 8.8 Heapsort.  Merge sort time is O(n log n) but still requires, temporarily, n extra storage locations  Heapsort does not require any additional.
CS 206 Introduction to Computer Science II 12 / 05 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 12 / 03 / 2008 Instructor: Michael Eckmann.
© 2006 Pearson Addison-Wesley. All rights reserved12 A-1 Chapter 12 Heaps.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L18 (Chapter 23) Algorithm.
Chapter 12 B Priority Queues. © 2004 Pearson Addison-Wesley. All rights reserved 12 B-2 The ADT Priority Queue: A Variation of the ADT Table The ADT priority.
Sorting Chapter 10. Chapter 10: Sorting2 Chapter Objectives To learn how to use the standard sorting methods in the Java API To learn how to implement.
Sorting Chapter 13 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Sorting II/ Slide 1 Lecture 24 May 15, 2011 l merge-sorting l quick-sorting.
Sorting Chapter 12 Objectives Upon completion you will be able to:
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
CHAPTER 09 Compiled by: Dr. Mohammad Omar Alhawarat Sorting & Searching.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Heaps, Heapsort, Priority Queues. Sorting So Far Heap: Data structure and associated algorithms, Not garbage collection context.
Sorting Chapter 10. Chapter Objectives  To learn how to use the standard sorting methods in the Java API  To learn how to implement the following sorting.
September 29, Algorithms and Data Structures Lecture V Simonas Šaltenis Aalborg University
Lecture 2 Sorting. Sorting Problem Insertion Sort, Merge Sort e.g.,
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
Merge sort, Insertion sort. Sorting I / Slide 2 Sorting * Selection sort (iterative, recursive?) * Bubble sort.
Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 26 Sorting.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Sorting.
CS 61B Data Structures and Programming Methodology July 21, 2008 David Sun.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Sorting part 2 Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
Exam #2 Review. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Week 13 - Friday.  What did we talk about last time?  Sorting  Insertion sort  Merge sort  Started quicksort.
Chapter 13 Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-in-first-out The “smallest”
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 25 Sorting.
Heaps © 2010 Goodrich, Tamassia. Heaps2 Priority Queue ADT  A priority queue (PQ) stores a collection of entries  Typically, an entry is a.
1 Chapter 8 Sorting. 2 OBJECTIVE Introduces: Sorting Concept Sorting Types Sorting Implementation Techniques.
Chapter 4, Part II Sorting Algorithms. 2 Heap Details A heap is a tree structure where for each subtree the value stored at the root is larger than all.
Sorting Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2010.
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
Quicksort Dr. Yingwu Zhu. 2 Quicksort A more efficient exchange sorting scheme than bubble sort – A typical exchange involves elements that are far apart.
Sorting part 2 Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Sorting Cont. Quick Sort As the name implies quicksort is the fastest known sorting algorithm in practice. Quick-sort is a randomized sorting algorithm.
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 23 Sorting.
Algorithms Sorting. Sorting Definition It is a process for arranging a collection of items in an order. Sorting can arrange both numeric and alphabetic.
Prof. U V THETE Dept. of Computer Science YMA
Sorting.
Description Given a linear collection of items x1, x2, x3,….,xn
Sorting Chapter 13 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Quicksort and Mergesort
Tree Representation Heap.
Ch. 8 Priority Queues And Heaps
Adapted from instructor resource slides
Sorting Dr. Yingwu Zhu.
Chapter 12 Heap ADT © 2011 Pearson Addison-Wesley. All rights reserved.
Heaps and priority queues
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Instructor: Dr. Michael Geiger Spring 2017 Lecture 36: Exam 3 Preview
Instructor: Dr. Michael Geiger Spring 2017 Lecture 30: Sorting & heaps
Presentation transcript:

Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Mergesort and Review Chapter 13 6/15/15

Today Any questions on project? Exams –Review questions –Easy question/fix (I added your points wrong) come see me in class. If you need a re-grade, follow instructions in syllabus. Come see me in office hours, or make an appointment Review Thursday Break More (new) Sorting Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

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

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

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

Selection Sort Solution Pass Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

7 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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Bubble Sort Algorithm 1. Initialize numCompares to n 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

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

Bubble Sort Solution Pass Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

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

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

Insertion Sort Example Pass Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

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

Insertion Sort Solution Pass keyji ,0 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ,1, , ,3,2,1

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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.

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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).

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

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

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 21 Heaps

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

23 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]

24 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

25 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

26 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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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]

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

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

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

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

Step 1 (ctd) Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

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

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

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

Step 2 (ctd) Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Swap 2. Prune

Continue the pattern Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

Continue the pattern Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

Continue the pattern Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

Complete! Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved

45 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

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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

48 Mergesort Algorithm

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 File File File 3

Mergesort Solution Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved File File File

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 51 O(n)

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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved 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

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

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

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