Tutorial_12_Sol-for-viewing-and-printing

Tutorial_12_Sol-for-viewing-and-printing -...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CC2203 Data Structures and Algorithms Sem 2, 2009-2010 Tutorial 12 Solution Exercise 1 answer (a) public int deleteMax(int[] mheap, int size) { // delete max element and return it if (size == 0) return -1; // if the max heap is empty // return a dummy integer -1 int max = mheap[0]; // max element // reheapify mheap[0] = mheap[--size]; heapify(mheap, 0, size); this.size = size; return max; } (Note: other correct algorithm is acceptable.) (b) (c) public void heapSort(int[] a, int size) { // sort the elements in the array a using the heap sort method int i; int[] temp_a = new int[size]; for (i = 0; i < size; i++) temp_a[i] = -1; MaxHeap temp = new MaxHeap(temp_a, size);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: temp.initializemheap(a, size); // create a max heap for (i = size - 1; i &gt; 0; i--) a[i] = temp.deleteMax(a, i+1); // extract the max element from the max heap } (Note: other correct algorithm is acceptable.) CC2203 Data Structures and Algorithms Sem 2, 2009-2010 (d) Elements in array are: 1, 2, 3, 5, 8, 10, 13, 21, 29, 34, 55, 89, 92, 99 Elements in max heap are: 99, 55, 92, 29, 34, 89, 13, 21, 5, 2, 8, 1, 10, 3 After removing the max from the max heap, the elements in the max heap are: 92, 55, 89, 29, 34, 10, 13, 21, 5, 2, 8, 1, 3 After sorting by heap sort, the elements in the max heap are: 1, 2, 3, 5, 8, 10, 13, 21, 29, 34, 55, 89, 92...
View Full Document

Page1 / 2

Tutorial_12_Sol-for-viewing-and-printing -...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online