【C++】堆排序

百科名片

堆排序(英語:Heapsort)是指利用堆這種數據結構所設計的一種排序算法。堆是一個近似完全二叉樹的結構,並同時滿足堆積的性質:即子結點的鍵值或索引總是小於(或者大於)它的父節點。

排序操作

在堆的數據結構中,堆中的最大值總是位於根節點(在優先隊列中使用堆的話堆中的最小值位於根節點)。堆中定義以下幾種操作:

  • 最大堆調整(Max Heapify):將堆的末端子節點作調整,使得子節點永遠小於父節點。
  • 創建最大堆(Build Max Heap):將堆中的所有數據重新排序。
  • 堆排序(HeapSort):移除位在第一個數據的根節點,並做最大堆調整的遞歸運算。

動圖演示

代碼實現

#pragma GCC optimize(3,"Ofast","inline")
#pragma G++ optimize(3,"Ofast","inline")

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>

#define RI                 register int
#define re(i,a,b)          for(RI i=a; i<=b; i++)
#define ms(i,a)            memset(a,i,sizeof(a))
#define MAX(a,b)           (((a)>(b)) ? (a):(b))
#define MIN(a,b)           (((a)<(b)) ? (a):(b))

using namespace std;

typedef long long LL;

const int N=1e6+5;

int n;
int a[N];

void max_heapify(int a[],int start,int end) {
	//建立父節點指標和子節點指標
	int dad=start;
	int son=dad<<1+1;
	while(son<=end) { 
		//若子節點指標在範圍內才做比較
		if(son+1<=end && a[son]<a[son+1]) son++;
		//先比較兩個子節點大小,選擇最大的
		if(a[dad]>a[son]) return;//如果父節點大於子節點代表調整完畢,直接跳出函數
			else { //否則交換父子內容再繼續子節點和孫節點比較
				swap(a[dad],a[son]);
				dad=son;
				son=dad<<1+1;
			}
	}
}
 
void heap_sort(int a[],int len) {
	//初始化,i從最後一個父節點開始調整
	for(int i=len>>1-1; i>=0; i--)
		max_heapify(a,i,len-1);
	//先將第一個元素和已經排好的元素前一位做交換,再從新調整(剛調整的元素之前的元素),直到排序完畢
	for(int i=len-1; i>0; i--) {
		swap(a[0],a[i]);
		max_heapify(a,0,i-1);
	}
}

int main() {
	scanf("%d",&n);
	for(int i=0; i<n; i++) scanf("%d",&a[i]);
	heap_sort(a,n);
	for(int i=0; i<n; i++) printf("%d ",a[i]);
    printf("\n");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章