notes88

notes88 - Heap Sort-uses a heap to do the sorting-heap is...

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

View Full Document Right Arrow Icon

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

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

Unformatted text preview: Heap Sort-uses a heap to do the sorting-heap is implemented in the same array void heapSort(int a, int n){ //a is the unsorted array of integers //n is the number of elements //PHASE 1: build heap, remove the elements from s & insert into heap for(int i=0; i<n; i++){ //insert i into heap //element i is now in the heap //we need to fix the heap from i to the root (upheap) int child = i; int parent = (child-1)/2; while(parent& gt;=0){ & nbsp; if(a[child] < a[parent]){ //inverted heap, do not change & nbsp; break; & nbsp; } & nbsp; //need to swap parent and child & nbsp; int temp = a[child]; & nbsp; a[child] = a[parent]; & nbsp; a[parent] = temp; & nbsp; //update parent and child & nbsp; child = parent; & nbsp; parent = (child-1)/2; } } //PHASE 2: remove max. element from heap & insert into s //fix heap (down heap), repeat for all elements for(int j = n-1; j >= 0; j--){ //swap max. and element in j int temp = a[0]; //always max. at zero a[0] = a[i]; a[j] = temp; //fix heap from the root to the bottom parent = 0; int left = 2*parent+1; int right = left+1; while(left < j){ //find max. child int child = left; if(right < j && a[child] < a[right]){ & nbsp; child = right; } //swap only if the child is larger than the parent if(a[parent] > a [child]){ //no more swapping needed break; } //we need to swap parent and child int temp = a[parent]; a[parent] = a[child]; a[child] = temp; parent = child; left = 2*parent+1; right = left+1; } } } Phase 1 and Phase 2: O(nlogn) + O(nlogn) = O(nlogn) Hashing -it maps a key to a record...
View Full Document

Page1 / 6

notes88 - Heap Sort-uses a heap to do the sorting-heap is...

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

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