码迷,mamicode.com
首页 > 其他好文 > 详细

堆排序(源码)

时间:2014-05-27 02:21:23      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:c   a   int   os   name   for   

源码:

//HeapSort.cpp

#include <iostream>
using namespace std;


//about heap:
//the last leaf node is a[n-1]
//the last non-leaf node is a[n/2-1];
// a[i]
// / \
// a[2i+1] a[2i+2]

//i: current node
//n: length of heap
int MaxHeapify(int a[],int i, int n)
{
int l = 2*i+1;
int r = 2*i+2;
int largest = i;
if (l<n && a[l]>a[i])
{
largest = l;
}
if (r<n && a[r]>a[largest])
{
largest = r;
}
if (largest != i)
{
int temp = a[i];
a[i] = a[largest];
a[largest] =temp;
MaxHeapify(a,largest,n);
}
return 0;
}
int BuildMaxHeap(int a[], int n)
{
//from the last non-leaf node.
for (int i=n/2-1; i>=0;i--)
{
MaxHeapify(a,i,n);
}
return 0;
}
void swap(int* i, int* j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
int Heapsort(int a[],int n)
{
BuildMaxHeap(a,n);
cout<<"After build max heap."<<endl;
for (int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
//output heap element
//from the root node.
for (int j=n-1;j>0;j--)
{
swap(&a[0],&a[j]); //a[j] is largest
MaxHeapify(a,0,j);
}
cout<<"After heap sort"<<endl;
for (int k=0; k<n;k++)
{
cout<<a[k]<<" ";
}
cout<<endl;

return 0;
}
int main()
{
int a[] ={6,3,8,9,7,20,12,7,5,3,2};
Heapsort(a,sizeof(a)/sizeof(a[0]));
system("pause");
return 0;
}

堆排序(源码),布布扣,bubuko.com

堆排序(源码)

标签:c   a   int   os   name   for   

原文地址:http://www.cnblogs.com/MayGarden/p/3736054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!