#include <iostream> using namespace std; int arr[] = {1,2,3,4,5,6 }; void swap(int& i, int& j) { int k = i; i = j; j = k; } void HeapAdjust(int array[], int i,const int length) { int lChild = i * 2; int rChild = i * 2 + 1; int max = i; if (i <= length / 2) { if (array[lChild - 1] > array[rChild - 1]) max = lChild; else max = rChild; if (array[max-1] > array[i - 1]) { swap(array[max-1], array[i - 1]); HeapAdjust(array,max,length); } } } int main() { int arrLen = sizeof(arr) / sizeof(arr[0]); for (int i = arrLen / 2; i > 0; i--) { HeapAdjust(arr, i, arrLen); } for (int i = arrLen; i > 2; i--) { swap(arr[0], arr[i-1]); HeapAdjust(arr, 1, i-2); } return 0; }
时间: 2024-10-05 16:00:51