1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <iostream>
using namespace std;
void heapIfy(int* num, int dad, int size) { int larger = 2*dad + 1; while(larger < size) { if(larger+1 < size && num[larger+1] < num[larger]) larger++;
if(num[larger] >= num[dad]) break;
swap(num[dad], num[larger]); dad = larger; larger = 2*dad + 1; } }
void _heapIfy(int* num, int dad, int size) { int larger = 2*dad + 1; if(larger >= size) return;
if(larger+1 < size && num[larger+1] < num[larger]) larger++;
if(num[larger] >= num[dad]) return;
swap(num[dad], num[larger]); _heapIfy(num, larger, size); }
void buildHeap(int* num, int size) {
for(int i = (size/2 - 1); i >= 0; i--) minHeapFixDown(num, i, size); }
void heapSort(int* num, int n) {
for(int i = n - 1; i >= 1; i--) { swap(num[i], num[0]); heapIfy(num, 0, i); } }
int main() { int num[10] = {9, 12, 17, 30, 50, 20, 60, 65, 4}; buildHeap(num, 10); heapSort(num, 10); for(int i = 0; i < 10; i++) cout << num[i] << " "; return 0; }
|