堆排序

来源:互联网 发布:软件测试脚本 编辑:程序博客网 时间:2024/06/02 00:50

sift_sort.h

#include<iostream>using namespace std;template <class T>int getArrayLen(T& array)//使用模板定义一 个函数getArrayLen,该函数将返回数组array的长度{    return (sizeof(array) / sizeof(array[0]));}template<class T>void sift(T *R,int low,int high)//构造堆方法{    int i=low,j=2*i;    T tmp = R[i];    while(j<high)    {        if (j < high-1 && R[j] < R[j+1])        {            j++;        }        if (tmp < R[j])        {            R[i] = R[j];            i = j;            j = 2*i;        }        else        {            break;        }    }    R[i] = tmp;}template<class T>void HeaderSort(T *R,int n){    T tmp;    for (int i=n/2-1;i>=0;--i)    {        sift(R,i,n);    }    for (int i=n-1;i>=1;--i)    {        tmp = R[0];        R[0]=R[i];        R[i]=tmp;        sift(R,0,i-1);    }}

测试用例

#include "sift_sort.h"int main(){    int a[]={1,2,3,4,5,4,3,2,8,3,9,12,1,4};    int len = getArrayLen(a);    HeaderSort(a,len);    for (int i=0;i<len;i++)    {        cout<<a[i]<<'\t';    }    getchar();    cout<<endl;    return 0;}
0 0
原创粉丝点击