zoukankan      html  css  js  c++  java
  • 堆排序改进

    上一篇是堆排序的简单过程,自认为下面这种更为合适:

    思想:

    1.建立大堆;

    2.取堆顶元素和堆尾元素交换;(此时,大堆已破坏,需要重新往下调整,恢复大堆)

    3.恢复大堆前,需要减掉已经在正确位置的堆尾元素;

    代码如下:

    #pragma once
    //
    //建立大堆,
    void AdjustUp(int *a, int index,int size)
    {
    	int child = index * 2 + 1;
    	while (child < size)
    	{
    		if ((child + 1) < size && a[child] < a[child + 1])
    		{
    			++child;
    		}
    
    		if (a[child] > a[(child - 1) / 2])
    		{
    			swap(a[child], a[index]);
    			index = child;
    			child = index * 2 + 1;
    		}
    		else
    		{
    			break;
    		}
    	}
    }
    
    
    void HeapSort(int *a,int size)
    {
    	assert(a);
    	//建大堆
    	for (int i = (size - 2) / 2; i >= 0; --i)
    	{
    		AdjustUp(a,i,size);
    	}
    
    	//排序
    	for (int i = 0; i < size; ++i)  //++i是因为控制后边的  保证每次最后一个数个堆顶数交换
    	{
    		swap(a[0], a[size-1-i]);
    		AdjustUp(a, 0,size-1-i);
    	}
    }


  • 相关阅读:
    haproxy的使用
    zookeeper 的多线程和单线程库使用对比
    zookeeper 简介
    将博客搬至CSDN
    Sublime Text 添加eclipse快捷键
    Atom编辑器添加eclipse快捷键
    Linux安装mysql教程
    设计模式
    设计模式
    设计模式
  • 原文地址:https://www.cnblogs.com/melons/p/5791868.html
Copyright © 2011-2022 走看看