This page provides a brief introduction to heap sort.
Definition
Heap sort (English: Heapsort) is a sorting algorithm designed using the data structure of a binary heap. The applicable data structure for heap sort is an array.
Process
Heap sort is essentially a selection sort based on a heap.
Sorting
First, build a max-heap. Then, take out the top element of the heap as the maximum value, swap it with the element at the end of the array, and maintain the properties of the remaining heap.
Next, take out the top element of the heap as the second largest value, swap it with the second-to-last element of the array, and maintain the properties of the remaining heap.
Repeat this process. After the \(n-1\)-th operation, the entire array is sorted.
Building a Binary Heap on an Array
Starting from the root node, arrange the nodes of each layer in the array.
Thus, for a node with index i in the array, the corresponding parent, left child, and right child nodes are as follows:
voidsift_down(intarr[],intstart,intend){// Calculate indices of parent and child nodesintparent=start;intchild=parent*2+1;while(child<=end){// Only compare when child index is within range// First compare the two children, choose the largestif(child+1<=end&&arr[child]<arr[child+1])child++;// If parent is greater than or equal to child, adjustment is complete, exit functionif(arr[parent]>=arr[child])return;else{// Otherwise, swap parent and child, then compare child with grandchildswap(arr[parent],arr[child]);parent=child;child=parent*2+1;}}}voidheap_sort(intarr[],intlen){// Start sift down from the parent of the last node to complete heapifyfor(inti=(len-1-1)/2;i>=0;i--)sift_down(arr,i,len-1);// First swap the first element with the element before the already sorted part,// then readjust (elements before the just-adjusted element) until sorting is completefor(inti=len-1;i>0;i--){swap(arr[0],arr[i]);sift_down(arr,0,i-1);}}
defsift_down(arr,start,end):# Calculate indices of parent and child nodesparent=int(start)child=int(parent*2+1)whilechild<=end:# Only compare when child index is within range# First compare the two children, choose the largestifchild+1<=endandarr[child]<arr[child+1]:child+=1# If parent is greater than or equal to child, adjustment is complete, exit functionifarr[parent]>=arr[child]:returnelse:# Otherwise, swap parent and child, then compare child with grandchildarr[parent],arr[child]=arr[child],arr[parent]parent=childchild=int(parent*2+1)defheap_sort(arr,len):# Start sift down from the parent of the last node to complete heapifyi=(len-1-1)/2whilei>=0:sift_down(arr,i,len-1)i-=1# First swap the first element with the element before the already sorted part,# then readjust (elements before the just-adjusted element) until sorting is completei=len-1whilei>0:arr[0],arr[i]=arr[i],arr[0]sift_down(arr,0,i-1)i-=1