Tutorial_12_Sol-for-viewing-and-printing

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

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

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

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

View Full Document
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 > 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

## This note was uploaded on 08/18/2011 for the course COMP 3868 taught by Professor Keithchan during the Summer '97 term at Hong Kong Polytechnic University.

### 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
Ask a homework question - tutors are online