标签:heap nbsp void lin int == api build --
1 inline int LEFT(int i) 2 { 3 return (i * 2 + 1); 4 } 5 6 inline int RIGHT(int i) 7 { 8 return (i * 2 + 2); 9 } 10 11 void swap(int &i, int &j) 12 { 13 int temp = i; 14 i = j; 15 j = temp; 16 } 17 18 void max_heapify(int a[], int n, int i) 19 { 20 int left = LEFT(i); 21 int right = RIGHT(i); 22 int max_idx = (left < n && a[i] < a[left]) ? left : i; 23 max_idx = (right < n && a[max_idx] < a[right]) ? right : max_idx; 24 if (i == max_idx) { 25 return; 26 } 27 swap(a[i], a[max_idx]); 28 max_heapify(a, n, max_idx); 29 } 30 31 void build_max_heap(int a[], int n) 32 { 33 for (int i = n / 2 - 1; i >= 0; i--) { 34 max_heapify(a, n, i); 35 } 36 } 37 38 void heap_sort(int a[], int n) 39 { 40 build_max_heap(a, n); 41 for (int i = n - 1; i > 0; i--) { 42 swap(a[i], a[0]); 43 max_heapify(a, i, 0); 44 } 45 }
标签:heap nbsp void lin int == api build --
原文地址:https://www.cnblogs.com/ren-yu/p/11832442.html