《算法导论》之堆排序学习心得

今天学习了《算法导论》第六章的堆排序,之前有人问我堆排序的核心思想是什么,当时真的懵了,作为一个经常编程的人来说,基本的数据结构都不清楚,真是惭愧,今天恶补。对于算法的分析过程就不再现眼,网上有很多大神都用浅显易懂的语言进行了分析,详见http://blog.csdn.net/morewindows/article/details/6709644。写这篇博文主要是把堆排序的代码实现贴出来,及自己编写代码中的错误和要注意的地方。

首先,教材上,所有的数组都是从1开始,因此,在编写代码时应注意容器或者数组的范围;第二,教材中伪码中的down to 2也应相应的减1,不过具体的是大于、大于等于或其他,要是情况而定。第三,这也是鄙人在编写代码时范的严重错误,没有仔细分析伪码,导致有些逻辑错误最终不能输出正确的结果。以下是实现代码:

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

#include "stdafx.h"
#include <vector>
#include <iostream>

using namespace std;

//--------
//insert a  node to the heap
// father node index is (i-1)/2
// son node index is (2*i+1) and (2*i+2)

//max heap
class heapSort
{
public:

	int heap_size;
	//--------
	void getheap_size(vector<int> &v)
	{
		heap_size = v.size() - 1;
	}
	//---------
	//input data of vector
	void intput(vector<int> &v)
	{

		cout << "Please input the data of heap :" << endl;
		int data;
		while (cin >> data)
		{
			v.push_back(data);
		}
	}

	//-------
	//make  i  root node
	void MAX_HEAPIFY(vector<int> &v, int i)
	{
		if (i > heap_size)
			cout << "overflow!!!" << endl;
		cout << heap_size << endl;
		int largest = i;
		

		//find the largest index of largest key
		if (((2 * i + 1) <= heap_size) && (v[2 * i + 1] > v[largest]))
			largest = 2 * i+1;    //left tree
		if (((2 * i + 2) <= heap_size) && (v[2 * i + 2] > v[largest]))
			largest = 2 * i + 2; //right tree

		if (largest != i)
		{
			int temp = v[i];
			v[i] = v[largest];
			v[largest] = temp;
			
			MAX_HEAPIFY(v, largest);
			
		}
		else
			cout << "This heap is already a max heap!" << endl;
	}


	//--------
	//creat max heap
	void Build_Max_Heap(vector<int> &v)
	{
		
		for (int i = heap_size / 2; i >= 0; --i)
		{
			MAX_HEAPIFY(v, i);
		}
		

	}

	//-------
	void HeapSort(vector<int> &v)
	{
		Build_Max_Heap(v);
		 
		for (int i = heap_size; i >= 1; --i)
		{
			int temp = v[0];
			v[0] = v[i];
			v[i] = temp;
			--heap_size;
			MAX_HEAPIFY(v,0);
		}

	}
	//--------
	void displayHeap(vector<int> &v)
	{
		for (vector<int>::iterator it = v.begin(); it != v.end();++it)
		{
			cout << *it << endl;
		}
	}
};



int _tmain(int argc, _TCHAR* argv[])
{
	heapSort myheap;
	vector<int> v;
	myheap.intput(v);
	myheap.getheap_size(v);
	//myheap.MAX_HEAPIFY(v, 3);
	//myheap.Build_Max_Heap(v);
	//myheap.displayHeap(v);
	myheap.HeapSort(v);
	myheap.displayHeap(v);

	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值