堆排序算法

 
 
#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <string.h>


void siftDown(int * str, int start, int end);
void heapify(int * str,int count);
void heapSort(int * str, int count);
void printStr(int * str, int count);
void exchange(int * str, int a, int b);

void printStr(int * str, int count)
{
    for(int i=0;i<count;i++)
    {
        std::cout<<str[i]<<" ";
    }
    std::cout<<std::endl;
}
void exchange(int * str, int a, int b)
{
    str[a]=str[a]+str[b];
    str[b]=str[a]-str[b];
    str[a]=str[a]-str[b];
}
void heapSort(int * str, int count)
{
    heapify(str, count);
    int end=count-1;
    while(end>0)
    {
        exchange(str,0,end);
        end--;
        siftDown(str,0,end);
    }
}
void heapify(int * str,int count)
{
    int start=(count-2)/2;
    while(start>=0)
    {
        siftDown(str,start,count-1);
        start--;
    }
}
void siftDown(int * str, int start, int end)
{
    int root=start;
    int swap;
    int child;
    while(root*2+1<=end)
    {
        child=root*2+1;
        swap=root;
        if(str[swap]<str[child])
        {
            swap=child;
        }
        if(child+1<=end&&str[swap]<str[child+1])
        {
            swap=child+1;
        }
        if(swap!=root)
        {
            exchange(str,swap,root);
            root=swap;
        }
        else
        {
            return;
        }
    }
}

int main()
{
    int str[8]={6,8,1,7,4,5,3,2};
    heapSort(str,8);
    printStr(str,8);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值