cpp-algo-cases/chapter_sorting/heap_sort.cpp

55 lines
1.3 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: heap_sort.cpp
* Created Time: 2023-05-26
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20>ѵij<D1B5><C4B3><EFBFBD>Ϊ n <20><><EFBFBD>ӽڵ<D3BD> i <20><>ʼ<EFBFBD><CABC><EFBFBD>Ӷ<EFBFBD><D3B6><EFBFBD><EFBFBD>׶ѻ<D7B6> */
void siftDown(vector<int> &nums, int n, int i) {
while (true) {
// <20>жϽڵ<CFBD> i, l, r <20><>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD><EFBFBD>Ľڵ㣬<DAB5><E3A3AC>Ϊ ma
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma])
ma = l;
if (r < n && nums[r] > nums[ma])
ma = r;
// <20><><EFBFBD>ڵ<EFBFBD> i <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> l, r Խ<><EFBFBD><E7A3AC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѻ<EFBFBD><D1BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (ma == i) {
break;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>
swap(nums[i], nums[ma]);
// ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD>¶ѻ<C2B6>
i = ma;
}
}
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void heapSort(vector<int> &nums) {
// <20><><EFBFBD>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѻ<EFBFBD><D1BB><EFBFBD>Ҷ<EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>нڵ<D0BD>
for (int i = nums.size() / 2 - 1; i >= 0; --i) {
siftDown(nums, nums.size(), i);
}
// <20>Ӷ<EFBFBD><D3B6><EFBFBD><EFBFBD><EFBFBD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>Ԫ<EFBFBD>أ<EFBFBD>ѭ<EFBFBD><D1AD> n-1 <20><>
for (int i = nums.size() - 1; i > 0; --i) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҷ<EFBFBD>ڵ㣨<DAB5><E3A3A8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA><EFBFBD><EFBFBD>βԪ<CEB2>أ<EFBFBD>
swap(nums[0], nums[i]);
// <20>Ը<EFBFBD><D4B8>ڵ<EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD>Ӷ<EFBFBD><D3B6><EFBFBD><EFBFBD>׽<EFBFBD><D7BD>жѻ<D0B6>
siftDown(nums, i, 0);
}
}
/* Driver Code */
int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
heapSort(nums);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɺ<EFBFBD> nums = ";
printVector(nums);
return 0;
}