堆——堆排序(C++实现)

关于堆

堆是一种数据结构;
 对于二叉堆,我们可以认为它是一个完全二叉树;对于一个以数组的方式存储的堆的完全二叉树来说,我们这样定义一个节点的下标:

parent(i)=i/2;

left(i)=2*i;

right(i)=2*I+1;

二叉堆可以分为两种形式:最大堆和最小堆;

大根堆:

在大根堆中,要求根节点的值最大,对任意节点有:A[i]≥A[left(i)]&&A[i]≥A[right(i)];即对于大根堆的二叉树的左右子树均为大根堆

小根堆
在小根堆中,要求根节点的值最小,对任意节点有:A[i]≤A[left(i)]&&A[i]≤A[right(i)];即对于小根堆的二叉树的左右子树均为小根堆

关于堆排序

堆排序是基于堆的性质实现的;

求降序使用小根堆排序,求升序用大根堆排序
堆排序是一种原址排序,时间复杂度为O(nlgn);

//【大根堆堆排序的实现】

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

int left(int i) { i = 2 * i; return  i; }
int right(int i) { i = 2 * i+1;return i; }

void max_heapify(int * b,int i,int heap_size)//最大堆的维修函数
{
	int l;
	int r;
	int largest;

	l = left(i);
	r = right(i);

	if ((l <= heap_size) && (b[l] > b[i])) largest = l;
	else largest = i;
	if ((r <= heap_size) && (b[r] > b[largest])) largest=r;
	else;
	if (largest != i)
	{
		int temp = b[i];
		b[i] = b[largest];
		b[largest] = temp;
		max_heapify(b, largest,heap_size);
	}
	else;
}
//建堆函数
void build_heap( int * a,int arylength)
{
	for(int i=arylength/2;i>0;i--)
	{
		max_heapify(a, i,arylength);
	}
	
}
//堆排序
void heap_sort(int * a, int heapsize) 
{
	
	build_heap(a,heapsize);
	for (int i = heapsize; i>1; i--)
	{
		int temp = a[1];
		a[1] = a[i];
		a[i] = temp;
		heapsize--;
		max_heapify(a, 1,heapsize);
	}
}
int main()
   {
	int length;
	cout << "please input the length of the array:\n ";
		cin >> length;
		int *ary = new int[length+1]; ary[0]=0;

	cout << "please input the array sequentially:\n";
		for (int i = 1; i <= length; i++) {cin >> ary[i];}

	cout <<endl<< "the array is:" << endl;
		for (int i = 1; i <= length; i++)
		{
			cout << ary[i]<<"  ";
		}
	build_heap(ary,length);

	cout <<endl<< "the max_heap is:" << endl;
		for (int i = 1; i <= length; i++)
		{
			cout << ary[i]<<"  ";
		}
	heap_sort(ary,length);

	cout <<endl<< "the result is:" << endl;
	    for (int i = 1; i <=length; i++){cout<< ary[i]<<"<=";}


return 0;
}






猜你喜欢

转载自blog.csdn.net/qq_42468130/article/details/80940334