排序 堆排序 例程

// heapSort.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<cstdlib>
using namespace std;

void MaxHeapify(int *a,int i,int size);				//保持最大堆特性
void BuildMaxHeap(int *a,int size)	;				//建立最大堆
void HeapSort(int *a,int size);							//堆排序
 inline int Parent(int i);							//算父节点
 inline int Left(int i);								//算左子节点
 inline int Right(int i);								//算右子节点
 void Display(int *a,int size) ;

int _tmain(int argc, _TCHAR* argv[])
{
	int size,*a;
	while(1)
	{
		cout<<"输入字符串长度:"<<endl;
		cin>>size;
		if(size > 0) {
			cout<<"请输入"<<size<<"个待排序数字:"<<endl;
			a = (int*)malloc(size*sizeof(int));//a = new int [size];
			for(int i=0; i<size; i++)
			{
				cin>>a[i];
			}
			HeapSort(a,size);
		}
		else
			cout<<"输入长度错误!"<<endl;

		Display(a,size);
	}
	return 0;
}

void MaxHeapify(int *a,int i,int size)				//保持最大堆特性
{
	int l,r,heapSize,largest,temp;
	l = Left(i);
	r = Right(i);
	heapSize =size;
	if (l<heapSize && a[l]>a[i] ) {
		largest = l;
	}
	else largest = i;

	if(r<heapSize && a[r]>a[largest]) {
		largest = r;
	}

	if(largest != i) {
		temp = a[i];
		a[i] = a[largest];
		a[largest] = temp;
		MaxHeapify(a,largest,heapSize);
	}

}

void BuildMaxHeap(int *a,int size)//建立最大堆
{
	int heapSize = size;
	int lengthArray =size;
	for(int i=lengthArray-1; i>=0; i--)
	{
		MaxHeapify(a,i,heapSize);
	}
}

void HeapSort(int *a,int size)				//堆排序
{
	int temp;
	int lengthArray = size;
	int heapSize = lengthArray;
	BuildMaxHeap(a,heapSize);
	for(int i=lengthArray-1; i>=1; i--)
	{
		temp = a[0];
		a[0] = a[i];
		a[i] = temp;
		heapSize -= 1;
		MaxHeapify(a,0,heapSize);
	}
}

inline int Parent(int i)//计算父节点
{
	i ++;
	return i/2-1;
}

inline int Left(int i)//计算子左节点
{
	i++;
	return 2*i-1;
}

inline int Right(int i)//计算子右节点
{
	i++;
	return 2*i;
}

void Display(int *a,int size)//打印函数
{
		for(int i=0; i<size; i++)    //打印数组
		{
			cout<<a[i]<<" ";
		}
		cout<<endl<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值