堆排序
作者:互联网
源码实现:
1 #include <iostream> 2 3 using namespace std; 4 5 void swap(int* pArry, int iNum, int x, int y) 6 { 7 int iTmp = 0; 8 9 if (NULL == pArry || 0 > x || 0 > y || iNum <= x || iNum <= y) 10 { 11 cout << "swap err happen!!" << endl; 12 return; 13 } 14 15 iTmp = pArry[x]; 16 pArry[x] = pArry[y]; 17 pArry[y] = iTmp; 18 19 return; 20 } 21 22 23 int heapfiy(int* pArry, int iNum, int iRootIdx) 24 { 25 int maxIdx = iRootIdx; 26 int lIdx = 2*iRootIdx + 1; 27 int rIdx = 2*iRootIdx + 2; 28 29 if (iNum > lIdx && pArry[lIdx] > pArry[maxIdx]) 30 { 31 maxIdx = lIdx; 32 } 33 if (iNum > rIdx && pArry[rIdx] > pArry[maxIdx]) 34 { 35 maxIdx = rIdx; 36 } 37 if (maxIdx != iRootIdx) 38 { 39 swap(pArry, iNum, iRootIdx, maxIdx); 40 41 if (0 != heapfiy(pArry, iNum, maxIdx)) 42 { 43 cout << "heapfiy, err!!!" << endl; 44 return -1; 45 } 46 } 47 48 return 0; 49 } 50 51 52 int heap_sort(int* pArry, int iNum) 53 { 54 int i = 0; 55 int j = 0; 56 int iTmp = 0; 57 58 /*先构造一个最大堆 59 * 整体上自底向上构造,堆最大值变化后内部从根到叶子进行递归更新 60 */ 61 for (i = (iNum/2 - 1); i >= 0; i--) 62 { 63 if (0 != heapfiy(pArry,iNum,i)) 64 { 65 cout << "err happen!!!" << endl; 66 return -1; 67 } 68 } 69 70 /*依次将最大值抽离到数组最后位置,再重新构造最大堆*/ 71 for (i = 1; i < iNum; i++) 72 { 73 swap(pArry, iNum, 0, iNum - i); 74 75 if (0 != heapfiy(pArry, iNum-i, 0)) 76 { 77 cout << "err happen!!!" << endl; 78 return -1; 79 } 80 } 81 82 return 0; 83 } 84 85 int print_arry(int* pArry, int iNum) 86 { 87 int i = 0; 88 if (NULL == pArry || 0 >= iNum) 89 { 90 return -1; 91 } 92 93 for (i =0; i < iNum; i++) 94 { 95 cout << pArry[i] << " "; 96 } 97 98 cout << endl; 99 100 return 0; 101 } 102 103 int main() 104 { 105 int orginArry[] = {11,34,65,67,234,4,1,3,6,3,2,100,41,56,43}; 106 int iNum = sizeof(orginArry)/sizeof(orginArry[0]); 107 108 cout << "orgin arry: " << iNum << endl; 109 (void)print_arry(orginArry, iNum); 110 111 if (0 != heap_sort(orginArry,iNum)) 112 { 113 cout << "err happen!!!" << endl; 114 return -1; 115 } 116 117 cout << "sort result:" << endl; 118 (void)print_arry(orginArry, iNum); 119 120 return 0; 121 }
运行结果:
算法理解:
1. 性能方面抽离最大值需要n数量级的循环,每次循环中heap的构建复杂度log(n),综合是nlog(n)的量级;
2. 算法的总体思想是,构建最大堆->找到最大值->剩下的进一步构建最大堆->再找次最大....依次递归;
标签:cout,int,堆排序,pArry,lIdx,iNum,maxIdx 来源: https://www.cnblogs.com/doctors/p/10423230.html