Www.monash.edu.au 1 COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been reproduced and communicated to you by or on behalf.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Heaps, Heap Sort, and Priority Queues. Sorting III / Slide 2 Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two.
Advanced Data Structures Chapter 16. Priority Queues Collection of elements each of which has a priority. Does not maintain a first-in, first-out discipline.
1 Sorting Problem: Given a sequence of elements, find a permutation such that the resulting sequence is sorted in some order. We have already seen: –Insertion.
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
CSE332: Data Abstractions Lecture 5: Binary Heaps, Continued Tyler Robison Summer
Priority Queue (Heap) & Heapsort COMP171 Fall 2006 Lecture 11 & 12.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Heaps and heapsort COMP171 Fall Sorting III / Slide 2 Motivating Example 3 jobs have been submitted to a printer in the order A, B, C. Sizes: Job.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
Lec 6 Feb 17, 2011  Section 2.5 of text (review of heap)  Chapter 3.
Chapter 6: Priority Queues Priority Queues Binary Heaps Mark Allen Weiss: Data Structures and Algorithm Analysis in Java Lydia Sinapova, Simpson College.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting an.
Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on MinHeap: Insert Delete Converting an array.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Lecture 7 Heaps and Priority Queues. Motivating Example 3 jobs have been submitted to a printer, the jobs have sizes 100, 10, 1 page. Average waiting.
Lecture 7 Heaps and Priority Queues. Motivating Example 3 jobs have been submitted to a printer, the jobs have sizes 100, 10, 1 page. Average waiting.
Lecture 11 Binary Heap King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
PQ, binary heaps G.Kamberova, Algorithms Priority Queue ADT Binary Heaps Gerda Kamberova Department of Computer Science Hofstra University.
Heaps and heapsort COMP171 Fall 2005 Part 2. Sorting III / Slide 2 Heap: array implementation Is it a good idea to store arbitrary.
1 Binary Heaps What is a Binary Heap? Array representation of a Binary Heap MinHeap implementation Operations on Binary Heaps: enqueue dequeue deleting.
1 Priority Queues (Heaps)  Sections 6.1 to The Priority Queue ADT  DeleteMin –log N time  Insert –log N time  Other operations –FindMin  Constant.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
The Binary Heap. Binary Heap Looks similar to a binary search tree BUT all the values stored in the subtree rooted at a node are greater than or equal.
Chapter 21 Binary Heap.
Chapter 7: Sorting Algorithms Insertion Sort. Sorting Algorithms  Insertion Sort  Shell Sort  Heap Sort  Merge Sort  Quick Sort 2.
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.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Dan Grossman Fall 2013.
1 Heaps (Priority Queues) You are given a set of items A[1..N] We want to find only the smallest or largest (highest priority) item quickly. Examples:
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Kevin Quinn Fall 2015.
CSE332: Data Abstractions Lecture 5: Binary Heaps, Continued Dan Grossman Spring 2012.
CS223 Advanced Data Structures and Algorithms 1 Priority Queue and Binary Heap Neil Tang 02/09/2010.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
1 COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been reproduced and communicated to you by or on behalf.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
1Computer Sciences. 2 HEAP SORT TUTORIAL 4 Objective O(n lg n) worst case like merge sort. Sorts in place like insertion sort. A heap can be stored as.
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
Heaps, Heap Sort, and Priority Queues. Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two children * A node that.
1 Priority Queues (Heaps)  Sections 6.1 to Priority Queues  Regular queues which supports –First In, First Out –Enqueue(): add a new element.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Heaps and Priority Queues What is a heap? A heap is a binary tree storing keys at its internal nodes and satisfying the following properties:
Heaps and Heap Sort. Sorting III / Slide 2 Background: Complete Binary Trees * A complete binary tree is the tree n Where a node can have 0 (for the leaves)
CSE373: Data Structures & Algorithms Priority Queues
CS 201 Data Structures and Algorithms
Priority Queues (Heaps)
Lecture No.45 Data Structures Dr. Sohail Aslam.
October 30th – Priority QUeues
Source: Muangsin / Weiss
Heaps, Heap Sort, and Priority Queues
Priority Queues (Heaps)
Binary Heaps What is a Binary Heap?
Heaps, Heap Sort, and Priority Queues
CMSC 341: Data Structures Priority Queues – Binary Heaps
CSE332: Data Abstractions Lecture 5: Binary Heaps, Continued
CMSC 341 Lecture 14 Priority Queues & Heaps
CE 221 Data Structures and Algorithms
CSE 332: Data Structures Priority Queues – Binary Heaps Part II
Priority Queues (Heaps)
Priority Queues CSE 373 Data Structures.
Heaps & Multi-way Search Trees
Priority Queues Binary Heaps
Priority Queues (Heaps)
Presentation transcript:

1 COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been reproduced and communicated to you by or on behalf of Monash University pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further reproduction or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice.

FIT2004 Algorithms & Data Structures L2: Revision - Divide & Conquer Prepared by: Bernd Meyer including revision material from FIT1008 February 2007

3 Overview Divide and Conquer Merge Sort (Revision) Quick Sort (Revision) Heap Structures Heap Sort

4 Search Divide and Conquer Search Search Recall: Binary Search

5 Sort Divide and Conquer Sorting SortSort SortSortSortSort

6 Divide and Conquer Combine CombineCombine

7 Divide and Conquer method sort(array) { if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) }

8 Merge Sort Sort Merge Split

9 public void mergeSort(int[] array) { int[] tmp = new int[array.length]; int from = 0, to = array.length-1; mergeSort(array, from, to, tmp); } Merge Sort method

10 void mergeSort(int[] array, int from, int to, int[] tmp) { if (from!=to) { int mid = (from + to)/2; mergeSort(array, from, mid, tmp); mergeSort(array, mid+1, to, tmp); mergeArrays(array, from, mid, to, tmp); for (int i = from; i <= to; i++) {array[i] = tmp[i];} } Merge Sort method

a: b: to: 10 tmp: Example: mergeArrays from: 0 mid: 5 32

a: tmp: ia=0 k=0 ib=6 3 Example: mergeArrays 32 b: 10

a: tmp: ia=0 k=0 3 ib=6 3 Example: mergeArrays 32 b: 10

a: tmp: ia=1ib=6 k= Example: mergeArrays 32 b: 10

a: 35 tmp: ia=2ib=6 k= Example: mergeArrays b:

a: 3510 tmp: ia=2ib=7 k= Example: mergeArrays b:

a: 3510 tmp: ia=2ib=8 k= Example: mergeArrays b:

a: 3510 tmp: ia=3ib=8 k= Example: mergeArrays b:

a: 3510 tmp: ia=3ib=9 k= Example: mergeArrays b:

a: 3510 tmp: ia=4ib=9 k= Example: mergeArrays b:

a: 3510 tmp: ia=5ib=9 k= Example: mergeArrays 32 b:

a: tmp: ia=6ib=11 k= Done! Example: mergeArrays 32 b:

23 protected void mergeArrays(int[] a, int from, int mid, int to, int[] tmp) { int ia = from, ib = mid+1; for (int k = from; k <= to; k++) { if (ia > mid) // a finished, copy b { tmp[k] = a[ib]; ib++;} else if (ib > to) // b finished, copy a { tmp[k] = a[ia]; ia++;} else if (a[ia] <= a[ib]) // a[ia] is the item to copy { tmp[k] = a[ia]; ia++;} else { tmp[k] = a[ib]; // b[ib] is the item to copy ib++;} } Example: mergeArrays

24 Merge Sort Analysis Most of the work is in the merging Takes O(n log(n)), where n is the number of elements in the array. Can you work out why? Uses more space than other sorts This is typically the method that you would naturally use when sorting a pile of books, CDs cards, etc.

25 Quick Sort x < ppp <= x Partition Sort

array: from:0 Example: Quick Sort to:10

array: “pivot element” 15 Example: Quick Sort mid = (from+to)/2 = 5

28 partition: array: index: 4 Example: Quick Sort

quickSort Example: Partition

30 void quickSort(int array[], int start, int size) { int index; if (from != to) { index = partition(array, from, to); quickSort(array, from, index); quickSort(array, index+1, to); } Quick Sort method

31 int partition(int[] array, int start, int to) { int mid = (from+to)/2; int index = from; swap(array,from,mid); for (int k = from+1; k <= to; k++) { if (array[k] < array[from]) { index++; swap(array,k,index); } swap(array,from,index); return index; } Partition method

32 Quick Sort Analysis Most of the work done in partitioning Need to be careful of choice of pivot –we will return to this in the algorithms’ analysis Average case takes O(n log(n)) time Worst case takes O(n 2 ) time

33 Summary Divide & Conquer Sorting Two Divide & Conquer Methods QuickSort –partition does (almost) all the work MergeSort –merge does (almost) all the work What is the general complexity of divide & conquer? >next lecture… Can we be any faster than this? –in terms of complexity classes? Big-Oh? >can we prove this? –how else?

34 Queues Recall: queues implement wait lists first-in-first-out principle easily implemented as lists ADT Queue sorts queue, elem, bool; ops empty:-> queue; isempty:queue-> bool; first: queue-> elem; enqueue:queue x elem -> queue; dequeue: queue-> queue; axioms … Note: this is parametric in the element type

35 Priority Queues Often you do not want FIFO but you have explicit priorities. Example: Reordering flight booking requests according to frequent flyer status New Operations “DeleteMin” extracts element with lowest priority ADT Queue sorts queue, elem, bool; ops empty:-> queue; isempty:queue-> bool; first: queue-> elem; enqueue:queue x elem -> queue; deleteMin: queue-> queue; axioms …

36 Priority Queues -- Trivial Implementation A Priority Queue can be implemented using a list and search. insert:O(1) deletemin = find + delete:O(n) can we be faster? We could use trees… you need to understand dynamic trees for this (later in unit), but it would be a bit of overkill here.

37 Heaps Use a Heap instead. A Heap is a binary tree that is completely filled with the possible exception fo the last level.

38 Heaps in Arrays As this structure is very regular, it can be easily represented in an array: parent a[I], left child a[2i], right child a[2i+1]

39 Heap Order Property To access the heap elements efficiently in priority order we need to maintain some sorted structure. Idea: DeleteMin - Minimum should be at root Order property: the parent p of every non-root node n has lower priority than n (or equal to).

40 Heap Order Property A Heap Not A Heap

41 Heap Class in Java … Why extends Comparable > ?

42 Heap Operations: Insert Idea: insert at first free position in bottom level, then let percolate upwards into correct position. (Example: insert 14)

43 Heap Operations: Insert (cont) Idea: insert at first free position in bottom level, then let percolate upwards into correct position.

44 Heap Operations: Insert

45 Heap Operations: DeleteMin Idea: Remove root, creating a whole. Re-insert last Element of heap by percolating down from root.

46 Heap Operations: DeleteMin (cont) Idea: Remove root, creating a whole. Re-insert last Element of heap by percolating down from root.

47 Heap Operations: DeleteMin (cont) Idea: Remove root, creating a whole. Re-insert last Element of heap by percolating down from root.

48 Heap Operations: DeleteMin

49 Heap Operations: DeleteMin (cont)

50 Heap Operations: DeleteMax It is easy to define a heap that has a deleteMax() operation instead of a deleteMin(). Exercise: Implement such a MaxHeap.

51 Heap Operations: Complexity Height of tree is O(log N) (complete tree has between 2 h and 2 h+1 -1 nodes) Insert: O(log N) worst case DeleteMin: O(log N) worst case

52 Heap Operations: re-ordering Other useful operations include decrease key increase key ie the re-assignment of priorities. How would you implement these? What are their complexities?

53 HeapSort A heap allows us to extract elements in sorted order. We can use it to sort a set of elements. Idea: 1.Build a heap of N elements 2.perform deleteMin() or deleteMax N times The deleted elements can be collected in a new array or (better) in the same array (“in situ”)

54 HeapSort - remove root element - store the deleted element (root=97) is stored in the position of the last heap element which has just been freed up (heap is one smaller) - percolate down the hole at the root

55 HeapSort in Java

56 HeapSort in Java

57 Building a Heap To create a heap from N items, we first create an arbitrary heap and then apply percolateDown() to each non-leaf node bottom- up. This effectively creaes small “sub-heaps” that are combined bottom-up. Bottom-up heap construction is more efficient than the naïve way (how?). Details see next lecture.

58 Building a Heap bottom-up

59 Building a Heap bottom-up

60 Building a Heap bottom-up

61 Building a Heap bottom-up

62 Reading Weiss, ( ), Sedgewick (part 1-4)