算法-堆排序-实现代码

作者: 1Z实验室阿凯 | 来源:发表于2016-02-28 14:44 被阅读39次
    //
    // Created by 富一鹏 on 16/1/30.
    //
    
    #include "main.h"
    #include <stdio.h>
    void exchange(int* a,int* b){
        int p=0;
        p=*a;
        *a=*b;
        *b=p;
    }
    
    void adjustHeap(int *number,int longs,int i){
        int left=2*i;
        int right=2*i+1;
        int max=i;
        if(right>longs){
            return;
        }
        if(number[left]>number[max]){
            max=left;
        }
        if(number[right]>number[max]){
            max=right;
        }
        if(max!=i) {
            exchange(&number[max],&number[i]);
            adjustHeap(number, longs, max);
        }
    }
    
    void buildHeap(int *number,int longs) {
        int i = longs / 2;
        for (; i > 0; i--) {
            adjustHeap(number, longs, i);
        }
    }
    int main()
    {
        char in[100];
        int count=0;
        int num=0;
        int number[100]={0};
        scanf("%s",in);
        for (int i = 0; i < sizeof(in) / sizeof(in[0]); ++i) {
            if(in[i]!='5'){
                num=in[i]-48+num*10;
            }else{
                number[count]=num;
                num=0;
                count++;
            }
        }
        buildHeap(number,count);
        for(int i=count;i>0;i--) {
            exchange(&number[1], &number[i]);
            adjustHeap(number,i-1,1);
        }
        for (int i = 1; i <= count; i++) {
            printf("%d ",number[i]);
        }
    }
    

    相关文章

      网友评论

        本文标题:算法-堆排序-实现代码

        本文链接:https://www.haomeiwen.com/subject/nkxgkttx.html