notes48

# notes48 - Heap Sort Feb 26th 2007 It is a sorting algorithm...

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

Heap Sort -- Feb. 26th, 2007 It is a sorting algorithm that uses the "heap" data structure. BTW, the name "heap" of this data structure has nothing to do with the memory area called "Heap" that is used to allocate memory using malloc or new. With the heap data structure, insert(key, data) takes O(log n) and removeMin(key, data) takes O(log n) Implementation of Heap Sort heap.h class HeapEntry{ public: int _key; void *data; } class Heap{ public: Heap(int maxSize); bool insert(int key, void *data); bool removeMin(int &key, void *&data); } void heapSortInt(int *array, int n){ //sort int array using heap sort that uses a heap data structure //Step 1 - create heap Heap *heap = new Heap(n); //Step 2 - put minimum element one by one into array for(int i = 0; i < n; i++){ int key; void *data; heap->removeMin(key, data); array[i] = key; //assign min key into array } delete heap; //we are done } Complexity of Heap Sort Step 1: Insert n elements into heap: n * O(log n) = O(n logn) Step 2: removeMin n element from heap and insert them into array: n * O(log n) = O(n logn) Total: O(n logn) This is better than bubble sort O(n^2), insertion sort O(n^2), selection sort O(n^2)

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

View Full Document
The implementation shown needs to allocate space for the heap, so the sort requires twice the space, array|heap. In bubble sort we use the array itself to do the sorting. That is called "in place" sorting. There is a variation of heap sort that uses the array to store both the heap and the unsorted array. In Place Heap Sort We use the same array to do the sorting. The array is divided into the heap H and an unsorted sequence S. Initially H is empty and S uses the whole array
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 7

notes48 - Heap Sort Feb 26th 2007 It is a sorting algorithm...

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

View Full Document
Ask a homework question - tutors are online