• 第6章 堆排序


    #include<stdio.h>
    #include<stdlib.h>
    #include<math.h>
    
    
    #define MAX_LEN 10
    
    
    
    void print(int* pArray, int size, char* c){
        printf("%s",c);
        for(int i = 0; i < size; ++i){
            printf("%d,",pArray[i]);
        }
    }
    
    void max_heap(int *pArray, int index, int size){
        int left_index = (index + 1) * 2 - 1;
        int right_index = (index + 1) * 2;
        int large;
        if(left_index < size && pArray[index] < pArray[left_index]){
            large = left_index;
        }
        else{
            large = index;
        }
        if(right_index < size && pArray[large] < pArray[right_index]){
            large = right_index;
        }
        
        if(large != index){
            int tmp = pArray[large];
            pArray[large] = pArray[index];
            pArray[index] = tmp;
            max_heap(pArray, large, size);
        }
    }
    
    
    
    void build_max_heap(int* pArray, int max){
        for(int i = ceil(max) / 2 - 1; i >= 0 ; --i){
            max_heap(pArray, i, max);
        }
    }
    
    void sort_heap(int* pArray, int max){
        int tmp = 0;
        for(; max; --max){
            build_max_heap(pArray, max);
            tmp = pArray[0];
            pArray[0] = pArray[max-1];
            pArray[max-1] = tmp;
        }
    }
    
    
    
    
    int main(void){
        int array[MAX_LEN];
        srand(100);
        for(int i = 0; i < MAX_LEN; ++i){
            array[i] = rand() * 100 / RAND_MAX;
        }
        print(array, MAX_LEN, "before sortheap is:
    ");
        sort_heap(array, MAX_LEN);
        print(array, MAX_LEN, "
    after sort_heap is:
    ");
      return 0; }
    运行结果:
    
    before sortheap is:
    1,3,16,50,74,34,75,5,70,17,
    after sort_heap is:
    1,3,5,16,17,34,50,70,74,75,
  • 相关阅读:
    结对编程作业——毕设导师智能匹配
    结对项目之需求分析与原型设计
    Excel绘制之甘特图
    Excel绘图之数据波动条形图
    Excel绘图之漏斗图
    Excel绘图之四象限散点图
    软件工程实践总结
    发送手机验证码
    个人作业——软件产品案例分析
    用例图
  • 原文地址:https://www.cnblogs.com/hebust-fengyu/p/10880323.html
Copyright © 2020-2023  润新知