1 //Max_heap and Priority queue2 //The index must be [1,size],not [0,size-1]3#include <iostream>4 using namespacestd;5 intarr[ -] = {1,4,2,3,9,7,8, -,Ten, -};6 #definePARENT (i) (I/2)7 #defineLeft (i) (i*2)8 #defineRight (i) (i*2+1)9 #defineERROR (-1)Ten //dump an array One voidDumpintArr[],intCNT) A { - for(intI=0; i<cnt;i++){ -cout<<arr[i]<<" "; the } -cout<<Endl; - } - + //ensure the Max heap time=o (LG (n)) - voidMax_heapify (intArr[],Const intSizeConst intindex) + { A intL=left (index), R=right (index), largest =index; at if(L<=size && arr[l-1] > arr[index-1]) largest=l; - if(R<=size && arr[r-1] > arr[largest-1]) largest=R; - if(Largest! =index) - { - intTMP = arr[largest-1]; -arr[largest-1] = arr[index-1]; inarr[index-1] =tmp; - max_heapify (arr,size,largest); to } + } - the //build Max_heap,time=o (n) * //if Index>size/2,arr[index] must be a leaf $ voidBuild_max_heap (intArr[],Const intsize)Panax Notoginseng { - for(inti=size/2;i>0; i--) the { + max_heapify (arr,size,i); A } the } + - //heap_sort,time=o (NLG (n)) $ voidHeap_sort (intArr[],intsize) $ { - inttmp; - for(intI=size;i>1; i--) the { -TMP = arr[0];Wuyiarr[0] = arr[i-1]; thearr[i-1] =tmp; -Max_heapify (arr,--size,1); Wu } - } About $ //return max key of Arr - intTopintArr[],Const intsize) - { - returnarr[0]; A } + the //return max key of arr and delete it - intPopintArr[],int&size) $ { the if(Size <1)returnERROR; the intmax = arr[0]; thearr[0] = arr[--size]; theMax_heapify (Arr,size,1); - returnMax; in } the the //increase the key of I About voidHeap_increase_key (intArr[],intIintkey) the { the if(Key < arr[i-1])return; thearr[i-1] =key; + while(i>1&& arr[i-1]>arr[parent (i)-1]) - { the intTMP = arr[i-1];Bayiarr[i-1] = Arr[parent (i)-1]; theArr[parent (i)-1] =tmp; thei =PARENT (i); - } - } the the //insert into priority queue the voidInsertintArr[],int&size,intkey) the { -size++; theArr[size] = key-1; the Heap_increase_key (arr,size,key); the }94 intMain () the { the intn =Ten; the build_max_heap (arr,n);98 dump (arr,n); About //Heap_sort (arr,n); - //dump (arr,n);101 pop (arr,n);102 dump (arr,n);103Insert (Arr,n, -);104 dump (arr,n); the return 0;106}
It is important to note that the heap sort is used (I/2) for the parent node, (2*i) for the left node, (2*i+1) for the right node, so the I in this is counted from 1, and our common array is counted from 0, so remember the subscript when calling the [] value operation-1
Heap Sort and Priority queue