C++ 堆排序 (HeapSort)

// HeapSort
/********************************************
 aim: to sort an array in ascending order.
 1. making a max-heap firstly(biggest on top). using siftup function (siftdown works as well if you like).
 2. sorting the heap by swapping the fisrt node(top) and the last node(leaf), so the last node is sorted.
 3. makeing a max-heap again for the rest of nodes(except for the sorted nodes(numbers)). 
 4. repeat step 2 and 3 for the unsorted nodes, until the number of sorted node is one.
 
 Note: I'm going to use siftup function, and the siftdown function will be presented as well, 
       these two functions do the same thing, you can choose anyone you like.
		
*********************************************/ 
#include <iostream>

using namespace std;


void SwapTwo(int &a, int &b)
{
	int temp = a;
	a = b;
	b= temp;
}

void siftup(int nums[], int i)     // comparation between the current node and its parent, swap two if necessary
{
	
	if(i==0) return;
	
	int p = (i-1)/2;
	
	if (nums[i]<nums[p]) return;
	
	else                          // if the node is larger than its parent, swap them and do siftup again to make sure 
	{                             // the node is less than it's new parent
		SwapTwo(nums[i], nums[p]);
		siftup(nums, p);
	}
}

/*
 void siftdown(int nums[], int i, int size)
 {
 int c = 2*i+1;
 if (c >= size) 
 {
 return;
 }
 
 if ((c+1<size) && (nums[c+1] > nums[c]))
 {
 c++;
 }
 if (nums[c] > nums[i])
 {
 SwapTwo(nums[c], nums[i]);
 siftdown(nums, c, size);
 }
 }
 */

// to make a max-heap(largest on top)
void MakeHeap(int nums[], int size)
{
	for (int i=0; i<size; i++)           // using siftup function
		siftup(nums, i);
	
	//for (int i=size-1; i>=0; i--)      // or you can use siftdown function
	//	siftdown(nums, i, size);
}


// to print an array
void Display(int nums[], int size)
{
	for (int i=0; i<size; i++)
	{
		cout << nums[i]<<endl;
	}
}

// to sort an array
void HeapSort(int nums[], int size)
{
	for (int i=size-1; i>=0; i--)
	{
		SwapTwo(nums[i], nums[0]);      // step 2, swapping the fisrt node(top) and the last node(leaf).
		size--;                         // remove the sorted numbers.
		MakeHeap(nums, size);           // make max-heap for unsorted numbers.
	}
}

int main() 
{
	int nums[10] = {34,4,56,67,78,5,345,234,435,456};
	
	int size = sizeof(nums)/sizeof(int);
	
	MakeHeap(nums, size);
	
	HeapSort(nums, size);
	
	Display(nums, size);
	
	return 0;
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值