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
| #include<iostream> #include<vector> using namespace std;
void adjust(vector<int> &arr, int len, int index) { int left = 2*index + 1; int right = 2*index + 2; int maxIdx = index; if(left<len && arr[left] > arr[maxIdx]) maxIdx = left; if(right<len && arr[right] > arr[maxIdx]) maxIdx = right; if(maxIdx != index) { swap(arr[maxIdx], arr[index]); adjust(arr, len, maxIdx); } }
void heapSort(vector<int> &arr, int size) { for(int i=size/2 - 1; i >= 0; i--) { adjust(arr, size, i); } for(int i = size - 1; i >= 1; i--) { swap(arr[0], arr[i]); adjust(arr, i, 0); } } int main() { vector<int> arr = {8, 1, 14, 3, 21, 5, 7, 10}; heapSort(arr, arr.size()); for(int i=0;i<arr.size();i++) { cout<<arr[i]<<endl; } return 0; }
|