堆排序算法,VS2005以验证

// SomeTest.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <math.h>
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;




inline int LEFT(int i);
inline int RIGHT(int i);
inline int PARENT(int i);
void MAX_HEAPIFY(int A[],int heap_size,int i);
void BUILD_MAX_HEAP(int A[],int heap_size);
void HEAPSORT(int A[],int heap_size);


int _tmain(int argc, _TCHAR* argv[])
{
const int MaxSize = 10;
int a[MaxSize+1];
a[0] = MaxSize;
srand((unsigned)time(NULL));//用当前时间,设置种子 
for (int i = 1;i<= MaxSize;i++)
{
a[i] = rand();
}
for (int i = 0;i<= MaxSize ;i++)
{
if (i % 6 == 0)
{
cout<<endl;
}
cout<<a[i]<<"   ";
}
cout<<endl;
//最坏时间复杂度为nLg(n)
HEAPSORT(a, a[0]);
for (int i = 0;i<= MaxSize ;i++)
{
if (i % 6 == 0)
{
cout<<endl;
}
cout<<a[i]<<"   ";
}
cout<<endl;
getchar();
return 0;
}






inline int LEFT(int i)
{
return 2 * i;
}
inline int RIGHT(int i)
{
return 2 * i + 1;
}
inline int PARENT(int i)
{
return i / 2;
}
void MAX_HEAPIFY(int A[],int heap_size,int i)
{
int temp,largest,l,r;
largest = i;
l = LEFT(i);
r = RIGHT(i);
if ((l <= heap_size) && (A[l] > A[largest])) largest = l;
if ((r<= heap_size) && (A[r] > A[largest])) largest = r;
if (largest != i)
{
temp = A[largest];
A[largest] = A[i];
A[i] = temp;
MAX_HEAPIFY(A,heap_size,largest);
}
}
void BUILD_MAX_HEAP(int A[],int heap_size)
{
int i;
for (i = heap_size / 2;i >= 1;i--) 
MAX_HEAPIFY(A,heap_size,i);
}
void HEAPSORT(int A[],int heap_size)
{
int i;
BUILD_MAX_HEAP(A,heap_size);
for (i = heap_size;i >= 2; i--)
{
int temp;
temp = A[1];
A[1] = A[i];
A[i]= temp;
MAX_HEAPIFY(A,i-1,1);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值