zoukankan      html  css  js  c++  java
  • 堆排序练习题

    #include <vector>
    using namespace std;
    class HeapSort
    {
    private:
    	int len;
    	vector<int> list;
    	void SwapNode(int i,int heapSize);
    public:
    	void Sort();
    	void Print();
    	HeapSort(void);
    	~HeapSort(void);
    };
    

    #include <iostream>
    #include "HeapSort.h"
    using namespace std;
    HeapSort::HeapSort(void)
    {
    	len = 10;
    }
    HeapSort::~HeapSort(void){}
    void HeapSort::SwapNode(int i,int heapSize)
    {
    	int l = i*2;
    	int r = i*2 +1 ;
    	
    	int max = i;
    	if(l<=heapSize && list[l-1] > list[i-1])
    		max = l;
    	if(r<=heapSize && list[r-1] > list[l-1])
    		max = r;
    	
    	if(max != i)
    	{
    		int tmp = list[max-1];
    		list[max-1] = list[i-1];
    		list[i-1] = tmp;
    		SwapNode(max,heapSize);
    	}
    }
    
    void HeapSort::Sort()
    {
    	for(int i=len/2;i>0;i--)
    	{
    		SwapNode(i,len);
    	}
    
    	int heapSize = len;
    	for(int i=len-1;i>0;i--)
    	{
    		int tmp = list[i];
    		list[i] = list[0];
    		list[0] = tmp;
    		SwapNode(1,--heapSize);
    	}
    }
    void HeapSort::Print()
    {
    	for(int i=0;i<len;i++)
    	{
    		int rnd = rand()%100;
    		list.push_back(rnd);
    		cout<<rnd << " ";
    	}
    	cout<<endl;
    	Sort();
    	for(int i=0;i<len;i++)
    	{
    		cout<<list[i]<<" ";
    	}
    	cout<<endl;
    }
    

    堆排序是默认把数组看作一个二叉树,第一步是把数组顺序按从小到大由顶向下调整(最大堆),

    第二步,取出堆(树)中的最后一个数,并把这个数放在堆顶,把最大的堆顶的数拿出。改变堆的元素个数(已经拿掉了个数),从新调整堆顶的那个比较小的数。

    第二步显然有大量无意义的对比。 大致看来 堆排序性能不高,复杂度最高最低都是nlogn

  • 相关阅读:
    Linux socket编程 服务器 客户端
    嵌入式编程 相关 细节 收集
    Linux内核运行机制学习笔记
    Button驱动学习
    LED驱动学习
    C#修改IIS匿名账号的密码问题
    数据库自增字段的获取
    VC头文件的顺序 以及一些常见错误的常见处理方式
    WIN8 更新CD KEY
    linux下 lvm 磁盘扩容
  • 原文地址:https://www.cnblogs.com/mad/p/heapsort.html
Copyright © 2011-2022 走看看