zoukankan      html  css  js  c++  java
  • 第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,
  • 相关阅读:
    FTP与HTTP上传文件的对比
    【FTP】Wireshark学习FTP流程
    【CSS】div
    浏览器URL中“#” “?” &“”作用
    【EF】vs2017中没有EF模型
    C# List的使用
    C# Dictionary使用
    Git/GitHub的一些问题
    PHP中的break与continue
    css使文字垂直水平居中
  • 原文地址:https://www.cnblogs.com/hebust-fengyu/p/10880323.html
Copyright © 2011-2022 走看看