您的位置:首页 > 编程语言 > C语言/C++

c++实现简单的建堆、维护堆和堆排序

2015-05-06 12:32 369 查看
// algorithms.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using std::cout;
using std::endl;
int heapSize;

void maxHeapIFY(int *,int);
void buildHeap(int *,int length);
void swap(int &, int &);
void heapSotr(int *);
int main()
{
int a[10] = { 121, 22, 13, 34, 53, 62, 71, 48, 59, 104};

heapSotr(a);

for (size_t i = 0; i < 10;i++)
{
cout << a[i] << " ";
}

return 0;
}
void buildHeap(int *a,int length){
heapSize = length - 1;
for (int i = length>>1; i >= 0; i--)
{
maxHeapIFY(a, i);
}
}
void maxHeapIFY(int *a,int i){
int l = (i << 1) + 1;
int r = (i << 1) + 2;
int largest;
if (l <= heapSize && a[i] < a[l])
{
largest = l;
}
else
{
largest = i;
}
if (r <= heapSize && a[largest] < a[r])
{
largest = r;
}
while (largest!=i)
{
swap(a[largest], a[i]);
i = largest;
int l = (i << 1) + 1;
int r = (i << 1) + 2;
if (l <= heapSize && a[i] < a[l])
{
largest = l;
}
else
{
largest = i;
}
if (r <= heapSize && a[largest] < a[r])
{
largest = r;
}
}
}
void swap(int &i, int &j){
int temp = i;
i = j;
j = temp;
}

void heapSotr(int *a)
{
buildHeap(a, 10);
for (int i = 9; i >= 1;i--)
{
swap(a[i], a[0]);
heapSize = heapSize - 1;
maxHeapIFY(a, 0);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法导论 c++ 堆排序