Download presentation
Presentation is loading. Please wait.
Published byMarcus Carroll Modified over 9 years ago
1
Max-Heapify Max_Heapify(A,i) { l=left(i) r=right(i) if(l A[i]) largest=l else largest=i if(r A[largest]) largest=r if(largest!=i) { exchange A[i] with A[largest] Max_Heapify(A.largest) }
2
Build Max Heap(A) void build_maxheap(int *a,int sz) { int i; for(i=sz/2;i>=0;i--) { Max_Heapify(a,i,sz); }
3
Heap_Sort(A) void heapsort(int *a, int sz) { int temp; build_maxheap(a,sz); while(sz>0) { exchange a[sz-1] with a[0] sz--; Max_Heapify(A,0,sz) }
4
2)Sort a nearly sorted (or K sorted) array Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. 1) Given a stream of numbers find k largest elements
5
Priority Queue A max priority queue supports the following operations: 1)Insert(S,x):- inserts the element x into the priority queue 2)Maximum(S):-returns the element with the largest key 3)Extract-Max(S):-removes and returns the element with the largest key 4)Increase Key(S,x,k):-increases the value of element x’s key to the new value k
6
Heap-Maximum return A[0] Heap-Extract-Max(A) { If(A.heapsize<1) error “heap underflow” Max=A[0] A[0]=A[A.heapsize-1] A.heapsize-- Max_Heapify(A,0) Return Max }
7
Heap-Increase-key(A,i,key) { A[i]=key while(i>0 and A[Parent(i)]<A[i]) exchange A[i]with A[Parent(i)] i=Parent(i) } Max-Heap-Insert(A,key) { A.heapsize++ A[A.heapsize]=-infinity Heap-Increase-key(A,A.heapsize,key) }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.