1 #include <iostream> 2 using namespace std; 3 4 int PARENT(const int &i){ 5 return (i>>2)-1; 6 } 7 8 int LEFT(const int &i){ 9 return (i<<1)+1; 10 } 11 12 int RIGHT(const int &i){ 13 return (i<<1) + 2; 14 } 15 16 void MAX_HEAPIFY(int *const A, const int &i,const int &heap_size){ 17 int l = LEFT(i); 18 int r = RIGHT(i); 19 int largest=i; 20 if (l < heap_size && A[l]>A[i]){ 21 largest = l; 22 } 23 else{ 24 largest = i; 25 } 26 27 if (r<heap_size && A[r]>A[largest]){ 28 largest = r; 29 } 30 if (largest != i){ 31 int key = A[i]; 32 A[i] = A[largest]; 33 A[largest] = key; 34 MAX_HEAPIFY(A, largest,heap_size); 35 } 36 } 37 38 void BUILD_MAX_HEAP(int *const A, const int &heap_size){ 39 for (auto i = heap_size / 2; i >= 0; --i){ 40 MAX_HEAPIFY(A, i, heap_size); 41 } 42 } 43 44 void swap2(int &a, int &b){ 45 int t = a; 46 a = b; 47 b = t; 48 } 49 50 void HEAP_SORT(int *const A, int &heap_size){ 51 BUILD_MAX_HEAP(A, heap_size); 52 for (auto i = heap_size-1; i > 0; --i){ 53 swap2(A[i], A[0]); 54 --heap_size; 55 MAX_HEAPIFY(A, 0, heap_size); 56 } 57 } 58 59 int main(void) 60 { 61 int a[] = { 16, 4, 10, 14, 7, 9, 3, 2, 8, 1 }; 62 int length = end(a) - begin(a); 63 HEAP_SORT(a, length); 64 system("pause"); 65 return 0; 66 }
时间: 2024-11-09 00:47:40