用C++写一个堆排序代码
时间: 2023-07-01 08:17:13 浏览: 102
好的,以下是用 C++ 写的堆排序代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 调整堆
void adjustHeap(vector<int>& nums, int root, int len) {
int left = 2 * root + 1; // 左子节点
int right = 2 * root + 2; // 右子节点
int maxIdx = root; // 最大值下标
if (left < len && nums[left] > nums[maxIdx]) {
maxIdx = left;
}
if (right < len && nums[right] > nums[maxIdx]) {
maxIdx = right;
}
if (maxIdx != root) {
swap(nums[root], nums[maxIdx]);
adjustHeap(nums, maxIdx, len);
}
}
// 堆排序
void heapSort(vector<int>& nums) {
int len = nums.size();
// 构建大根堆
for (int i = len / 2 - 1; i >= 0; i--) {
adjustHeap(nums, i, len);
}
// 排序
for (int i = len - 1; i >= 0; i--) {
swap(nums[0], nums[i]);
adjustHeap(nums, 0, i);
}
}
int main() {
vector<int> nums = { 5, 2, 8, 3, 9, 4, 1, 7 };
heapSort(nums);
for (auto num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
```
以上代码实现了堆排序,主要包含两个函数:`adjustHeap` 和 `heapSort`。
`adjustHeap` 函数用于调整堆,其中 `root` 参数表示当前节点的下标,`len` 参数表示堆的长度。该函数会将以 `root` 为根节点的子树调整为大根堆。
`heapSort` 函数用于堆排序,其中先构建大根堆,然后从后往前遍历数组,每次将第一个元素(即堆的根节点)与当前位置的元素交换,并调整堆。最终得到的数组就是排好序的。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)