算法导论笔记(一) :堆排序

来源:互联网 发布:手机淘宝详情页怎么做 编辑:程序博客网 时间:2024/05/16 10:49

1 完全二叉树与堆

一颗高度为h的树.如果前h-1层为满二叉树,并且第h层的叶子节点均集中在左侧.这样的树称为完全二叉树.

堆可以被视为完全二叉树.给定了每个节点的下标i,其父节点PARENT(i),左儿子LEFT(i)和右儿子(i)的下标可以简单的被计算出来:


2 堆的数组表示

堆可以表示为一个完全二叉树 或者一个数组.圆圈内是节点的值,圆圈上是节点在数组中的位置.根节点的高度为0.


3 最大堆与最小堆

最大堆是指除了根节点外.所有子节点的值都不能大于父节点.最小堆与其相反.

在堆排序中通常使用最大堆.而在优先级队列中通常使用最小堆.

4 堆排序的基本过程

(i)   MAX-HEAPIFY 过程. 运行时间是O(lgn).该过程使堆保持为最大堆.

(ii)  BUILD-MAX-HEAP. 运行时间是O(n). 可以在无序的输入数组上构造出最大堆.

(iii) HEAPSORT.堆排序的主过程.运行时间是O(nlgn).对一个数组进行原地排序.

5 完整代码

(i)定义堆排序类

#ifndef __HEAPSORT_H__#define __HEAPSORT_H__#include <stdlib.h>#include <stdio.h>#include <time.h>class Heapsort{  int* m_data;  int  m_heapSize;  bool b_created;public:  Heapsort();  Heapsort(int* inputData,int size);  ~Heapsort();  void Create(int size);  void Distroy();  void Build_Max_Heap();  void Max_Heapify(int nodeIndex,int currentHeapSize);  void Sort();  bool Verify();};#endif

(ii)类的实现

#include "Heapsort.h"Heapsort::Heapsort(){  m_data = NULL;  m_heapSize = 0;  b_created = false;}Heapsort::Heapsort(int* inputData,int size){  m_data = inputData;  m_heapSize = size;  b_created = false;}Heapsort::~Heapsort(){  if(b_created)  {    Distroy();  }  m_data = NULL;}void Heapsort::Create(int size){  m_data = (int *)malloc(sizeof(int) * size);  m_heapSize = size;  srand((unsigned)time(NULL));  for(int i=0;i< m_heapSize;i++)  {    m_data[i] = rand();  }  b_created = true;}void Heapsort::Distroy(){  free(m_data);}void Heapsort::Max_Heapify(int nodeIndex,int currentHeapSize){  int largest,tmpSwap;  int left_index = (nodeIndex<<1)+1;  int right_inde = left_index+1;  if(left_index<currentHeapSize && m_data[left_index]>m_data[nodeIndex])  {    largest = left_index;  }  else  {    largest = nodeIndex;  }  if(right_inde<currentHeapSize && m_data[right_inde]>m_data[largest])  {    largest = right_inde;  }  if(largest != nodeIndex)  {    tmpSwap = m_data[nodeIndex];    m_data[nodeIndex] = m_data[largest];    m_data[largest] = tmpSwap;    Max_Heapify(largest,currentHeapSize);  }}void Heapsort::Build_Max_Heap(){  for(int i=(m_heapSize>>1)-1;i>=0;i--)  {    Max_Heapify(i,m_heapSize);  }}void Heapsort::Sort(){  int tmpSwap;  int current_heap_size = m_heapSize;  Build_Max_Heap();  for(int i = m_heapSize-1;i>0;i--)  {    tmpSwap = m_data[0];    m_data[0] = m_data[i];    m_data[i] = tmpSwap;    current_heap_size--;    Max_Heapify(0,current_heap_size);  }}bool Heapsort::Verify(){  int newValue;  int oldValue = m_data[0];  for(int i=1;i<m_heapSize;i++)  {    newValue = m_data[i];    if(newValue<oldValue)    {      return false;    }    oldValue = newValue;  }  return true;}


(iii)测试程序

#include "Heapsort.h"int main(){  int heapSize = 1000 * 1000;  Heapsort pSort;  pSort.Create(heapSize);  pSort.Sort();  if(pSort.Verify())  {    printf("Success \n");  }  else  {    printf("Error \n");  }return 0;}


0 0
原创粉丝点击