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)