算法導論 第六章:堆排序

(二叉)堆數據結構是一種數組對象,如下圖所知,他可以被視爲一顆完全二叉樹。

其有如下性質:

1)對於i節點(i表示下標),其父節點爲Li/2」,左孩子節點爲2i,右孩子節點爲2i+1

2)最大堆滿足:A[PARENT(i)] ≥ A[i] ;最小堆滿足:A[PARENT(i)] ≤ A[i]

3)堆的高度爲:Θ(lgn)

4)子數組元素A[ (Ln/2」+1)...n]是樹中的所有葉子節點

維持堆的性質

以最大堆爲例,當節點i違反了最大堆的性質,則需從節點i處“下降”以調整堆。僞代碼如下:

其時間複雜度爲:T(n)=O(h)

EG:

建堆

根據上述性質4,對於數組A,建堆僞代碼如下:

其時間複雜度爲:T(n)=O(n)

堆排序

僞代碼如下:

其時間複雜度爲:T(n)=O(nlgn)

EG:

......

堆排序完整代碼如下:

#include<iostream>
#define PARENT(i) (i/2)
#define LEFT(i)   (2*i)
#define RIGHT(i)  (2*i+1)
using namespace std;

void Print(int *a,int n)
{
	for(int i=1;i<=n;i++)
		cout<<a[i]<<"   ";
	cout<<endl;
	}
int *Transform(int *a,int n)
{
  int * A=new int[n+1];
   A[0]=n;
   for(int i=0;i<n;i++)
	   A[i+1]=a[i];
   return A;	
	}
void swap(int &a,int &b)
{
	int temp;
	temp=a;
	a=b;
	b=temp;
	}
void Max_Heapify(int *A,int i)
{//adjust the heap to maintain the heap property
	int heap_size=A[0];
	int l=LEFT(i) ;   //index of i's left child
	int r=RIGHT(i);
	int largest;     //At each step,the largest of the element A[i],A[LEFT(i)]
					 //A[RIGHT(i)] is determined,and its index is stored in largest. 

	if(l<=heap_size && A[l]>A[i])
		largest	= l;
	else
		largest = i;

	if(r<=heap_size && A[r]>A[largest])
		largest = r;
	
	if(largest!=i)     //the subtree rooted at i violate the max-heap property
	{
		swap(A[i],A[largest]);
		Max_Heapify(A,largest);  //after exchanging ,the subtree rooted at largest might violate the max-heap property
		}
	}
void Build_MaxHeap(int *A)
{//Transform array A into max-heap A,where A[0]=heap-size
	int A_length=A[0];
	for(int i=A_length/2;i>=1;i--)
		Max_Heapify(A,i);	
	}
void Heap_Sorting(int *A)
{
	Build_MaxHeap(A);
	int heap_size=A[0];
	for(int i=heap_size;i>=2;i--)
	{ 
		swap(A[1],A[i]);
		heap_size--;
		A[0]=heap_size;   //After build-maxheap,A[0] store the heap-size,which is changing
		Max_Heapify(A,1);//adjust the heap to be max-heap from the root
		}
	}
int main(){
	
	int a[]={4,1,3,2,16,9,10,14,8,7};
	int n=sizeof(a)/sizeof(int);
	int *A=new int[n+1];
	cout<<"Before Sorting A[1..n]:"<<endl;
	A=Transform(a,n);   //Transform a[0...n-1] into a[1...n];a[0]=a.length
	Print(A,n);
	
	cout<<"After Heap_Sorting A[1..n]:"<<endl;
	Heap_Sorting(A);
	Print(A,n);

	return 0;
	}

運行結果:


[注:若有錯誤,請指正~]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章