堆排序
作者:互联网
#include<iostream> #include<cstdlib> #include<stack> #include<string> #include<vector> using namespace std; void HeapAdjust(vector<int> &A, int beginIndex, int endIndex){ int temp = A[beginIndex]; int j = 2 * beginIndex; for(; j <= endIndex; j = j * 2){ //在左右子节点中选一个更大的节点 if(j < endIndex && A[j] < A[j+1]) j++; //比较子节点和父节点 //如果父节点大于子节点break if(temp >= A[j]) break; //如果父节点小于子节点,将子节点的值赋给父节点 A[beginIndex] = A[j]; beginIndex = j;//对变动的子树进行进一步调整 } A[beginIndex] = temp; } void HeapSort(vector<int> &A,int len){ //构建一棵最大堆二叉树 //从最后一个有子节点的数开始构造 for(int i = (len-1)/2; i >= 0; i--){ HeapAdjust(A,i,len-1); } //将最大堆的堆顶与最后一个位置交换,继续调整堆 for(int i = len - 1; i > 0; i--){ swap(A[0],A[i]); HeapAdjust(A,0,i-1); } } int main() { vector<int> A = {5,2,7,3,6,1,4,8}; HeapSort(A,A.size()); for(int i = 0; i < A.size(); i++){ cout<<A[i]<<" "; } }
标签:beginIndex,int,堆排序,len,HeapAdjust,include,节点 来源: https://www.cnblogs.com/buaaZhhx/p/12077856.html