第6章 论堆排序

来源:互联网 发布:vue.js可以做什么 编辑:程序博客网 时间:2024/09/21 08:59
堆排序可以再O(nlogn)的时间内将数进行排序,不像归并排序,它是一种原地排序算法。
// 堆排序.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream>using namespace std;/*保持最大堆性质程序,时间复杂度为O(logn)*/void Max_heapify(int a[],int i,int heap_size){int l=2*i;int r=2*i+1;int largest;if(l<=heap_size&&a[l]>a[i])largest=l;elselargest=i;if(r<=heap_size&&a[r]>a[largest])largest=r;if(largest!=i){int temp=a[i];a[i]=a[largest];a[largest]=temp;Max_heapify(a,largest,heap_size);}}/*建立最大堆,由于Max_heapify()共调用O(n)次,所以时间复杂度为o(nlogn)*/void Build_Max_Heap(int a[],int n){int heap_size=n;for(int i=n/2;i>=1;i--)Max_heapify(a,i,heap_size);}/*堆排序算法*/void HeapSort(int a[],int n){int heap_size=n;Build_Max_Heap(a,n);for(int i=n;i>=2;i--){int temp=a[1];a[1]=a[i];a[i]=temp;heap_size--;Max_heapify(a,1,heap_size);}}int _tmain(int argc, _TCHAR* argv[]){int a[]={0,4,1,3,2,16,9,10,14,8,7};HeapSort(a,10);for(int i=1;i<=10;i++)cout<<a[i]<<" ";cout<<endl;return 0;}