https://www.cnblogs.com/MOBIN/p/5374217.html
https://www.cnblogs.com/chengxiao/p/6194356.html
堆排序是一种选择排序,它的最坏,最好,平均时间复杂度均为O(nlogn),它是不稳定排序。
一般升序采用大顶堆,降序采用小顶堆。
1 //HeapSort堆排序 2 void Swap(int a[], int i, int j) 3 { 4 int temp = a[i]; 5 a[i] = a[j]; 6 a[j] = temp; 7 } 8 9 void AdjustHeap(int a[], int i, int index) //调整为大顶堆:升序使用大顶堆,降序使用小顶堆 10 { 11 int left, right, j; 12 while ((left = 2*i+1) <= index) 13 { 14 right = left + 1; 15 j = left; 16 if (j < index && a[left] < a[right]) 17 { 18 j++; 19 } 20 if (a[i] < a[j]) 21 { 22 Swap(a, i, j); 23 i = j; //如果进行了交换,需要再重新对该非叶子节点及其儿子进行调整 24 } 25 else 26 { 27 break; 28 } 29 } 30 } 31 32 void HeapSort(int a[], int len) 33 { 34 int index = len -1; 35 int i = index / 2 -1; 36 for (; i >= 0; i--) 37 { 38 AdjustHeap(a, i, index); 39 } 40 41 while (index > 0) 42 { 43 Swap(a, 0, index--); 44 AdjustHeap(a, 0, index); 45 } 46 }
测试:
1 int _tmain(int argc, _TCHAR* argv[]) 2 { 3 int a[7] = {5,3,7,4,8,1,10}; 4 //QuickSort2(a, 0, 6); 5 //BubbleSort(a, 7); 6 HeapSort(a, 7); 7 for (int i = 0; i < 7; i++) 8 { 9 printf("%4d", a[i]); 10 } 11 return 0; 12 }