堆排序(heap Sort)

本文详细介绍了一种高效的排序算法——堆排序。首先通过构建最大堆来组织输入数据,然后通过不断交换根节点与堆中最后一个元素并调整堆结构来实现排序过程。文章提供了完整的堆排序算法代码实现,并解释了关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Algorithm steps:

1. Build a max heap from the input data.

2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing     the size of heap by 1. Finally, heapify the root of tree.

3. Repeat above steps while size of heap is greater than 1.


#include <bits/stdc++.h>
 
using namespace std;
const int MAXN = 1024;
int arr[MAXN];

void heapify(int arr[], int n, int i) {
 	int maxIdx = i;
 	int l = i * 2 + 1;
 	int r = i * 2 + 2;
 	if(l < n && arr[l] > arr[maxIdx]) {
 	 	maxIdx = l;
 	}
 	if(r < n && arr[r] > arr[maxIdx]) {
 	 	maxIdx = r;
 	}
 	if(maxIdx != i) {
 	 	swap(arr[i], arr[maxIdx]);
 	 	heapify(arr, n, maxIdx);
 	}
}

void buildHeap(int arr[], int n) {
 	for(int i = n/2 - 1; i >= 0; --i) {
 	 	heapify(arr, n, i);
 	}
}

void heapSort(int arr[], int n) {
 	buildHeap(arr, n);
 	for(int i = n-1; i >= 0; --i) {
 	 	swap(arr[0], arr[i]);
 	 	heapify(arr, i, 0);
 	}
}

int main(){
    ios::sync_with_stdio(false);
    int T;
    cin >> T;
    while(T--) {
     	int n;
     	cin >> n;
     	for(int i = 0; i < n; ++i) {
     	 	cin >> arr[i];
     	}
     	heapSort(arr, n);
       	for(int i = 0; i < n; ++i) {
     	 	cout << arr[i] << " ";	
     	}
     	cout << endl;
    }
    return 0;   
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值