堆排序

来源:互联网 发布:wince电子狗软件 编辑:程序博客网 时间:2024/06/05 07:13

        堆排序利用树形结构建立最小堆或者最大堆,可以利用数组结构方便的实现。

        升序排列过程如下:

      

/************************************    这是一个针对数组的堆排序过程,该过程建立的是一个最大堆,因此排序默认采用的是升序。************************************/#ifndef Heap_Sort_H#define Heap_Sort_H//单个节点调整过程template <typename Type>void AdjustHeap(Type array[],int index,int array_length){int lchild=2*index+1;//如果存在左右子节点if(lchild+1<array_length){if(array[lchild]<array[lchild+1])++lchild;if(array[lchild]>array[index]){//找到该节点与左右子节点最大的节点,交换到根节点位置Type temp=array[lchild];array[lchild]=array[index];array[index]=temp;}}    //只存在左子节点else{if(array[lchild]>array[index]){//左子结点大,进行交换Type temp=array[lchild];array[lchild]=array[index];array[index]=temp;}}}//建堆template <typename Type>void MakeHeap(Type array[],int length){for(int i=length/2-1;i>=0;--i)AdjustHeap(array,i,length);}//堆排序过程template <typename Type>void HeapSort(Type array[],int length){//构建堆结构MakeHeap(array,length);for(int i=length-1;i>0;--i){Type temp=array[i];array[i]=array[0];array[0]=temp;MakeHeap(array,i);}}#endif


    降序排列过程如下:

       

/************************************    这是一个针对数组的堆排序过程,该过程建立的是一个最小堆,因此排序默认采用的是降序。************************************/#ifndef Heap_Sort_H#define Heap_Sort_H//单个节点调整过程template <typename Type>void AdjustHeap(Type array[],int index,int array_length){int lchild=2*index+1;//如果存在左右子节点if(lchild+1<array_length){if(array[lchild]>array[lchild+1])++lchild;if(array[lchild]<array[index]){//找到该节点与左右子节点最大的节点,交换到根节点位置Type temp=array[lchild];array[lchild]=array[index];array[index]=temp;}}    //只存在左子节点else{if(array[lchild]<array[index]){//左子结点大,进行交换Type temp=array[lchild];array[lchild]=array[index];array[index]=temp;}}}//建堆template <typename Type>void MakeHeap(Type array[],int length){for(int i=length/2-1;i>=0;--i)AdjustHeap(array,i,length);}//堆排序过程template <typename Type>void HeapSort(Type array[],int length){//构建堆结构MakeHeap(array,length);for(int i=length-1;i>0;--i){Type temp=array[i];array[i]=array[0];array[0]=temp;MakeHeap(array,i);}}#endif


        由于堆排序建堆需要较多的比较次数,因此不适合记录数较少的情况。它是一种就地排序方法,时间复杂度为O(N*logN),属于不稳定的排序方法!

0 0