LKB的专栏

学习笔记,感悟,心得

堆排序

 

示意图如下:

                           

 

 

 

 

代码如下:

   

#include<iostream>
#include<iomanip>

using namespace std;

void keep_heap(int arr[], int i,int heap_size)
{
	int Left = i * 2;
	int Right = 2 * i +1 ;
	int largest=i;
	if (Left < heap_size && arr[Left] > arr[i])
	    largest = Left;
	else
		largest = i;
	if (Right < heap_size && arr[Right] > arr[largest])
		largest = Right;
	if (largest != i)
	{
		int t = arr[i];
		arr[i] = arr[largest];
		arr[largest] = t;
		keep_heap(arr, largest, heap_size);
	}
	
}


void build_heap(int arr[], int heap_size)
{

	for (int i = heap_size / 2 - 1; i >= 1; i--)
	{
		keep_heap(arr, i, heap_size);
	}


}

void heap_sort(int arr[], int n)
{
	int heap_size = n;
	build_heap(arr, heap_size);
	for (int i = n-1; i >= 1; i--)
	{
		int t = arr[1];
		arr[1] = arr[i];
		arr[i] = t;
		heap_size--;
		keep_heap(arr, 1, heap_size);
	}


}

void main()
{
	int arr[] = { 0, 9, 5, 7, 8, 6, 2, 4, 3, 1 };
	int length = sizeof(arr) / sizeof(int);
	for (int i = 1; i < length; i++)
		cout << arr[i] << " ";
	cout << endl;

	heap_sort(arr, length);
	for (int i = 1; i < length; i++)
		cout << arr[i] << " ";
	cout << endl;
	system("pause");
}


 

 

 

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26919527/article/details/49914215
文章标签: 堆排序
个人分类: 算法
上一篇杭电acm--2187
下一篇基数排序
博主设置当前文章不允许评论。

没有更多推荐了,返回首页

关闭
关闭