zoukankan      html  css  js  c++  java
  • 堆排序

    堆排序

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    
    void max_heapify(int arr[], int start, int end) {
        int dad = start; int son = dad * 2 + 1;
    
        while ( son <= end ){
            if (son + 1 <= end && arr[son] < arr[son+1]){
                son++;
            }
            if (arr[dad] > arr[son]){
                return;
            } else {
                swap(arr[dad], arr[son]);
                dad = son; 
                son = dad * 2 + 1;
            }
        }
    }
    
    void heap_sort(int arr[], int length){
        for(int i = length / 2 - 1; i >= 0; i--){
            max_heapify(arr, i, length-1);  // 这样的话是大堆顶
        }
        for(int i = length - 1; i >= 0; i--){
            swap(arr[0], arr[i]);
            max_heapify(arr,0,i-1);
        }
    
    }
    
    int main(){
        int arr[] = { 4,6,1,32,56,7,2,3,5,3};
        int length  = sizeof(arr) / sizeof(*arr);
        heap_sort(arr, length);
        for(int i = 0; i < length; i++){
            cout << arr[i]  << "   ";
        }
        system("pause");
        return 0;
    }
    

    堆排序时间复杂度分析

    堆排序是一种选择排序,整体主要由构建初始堆+交换堆顶元素末尾元素并重建堆两部分组成。其中构建初始堆经推导复杂度为O(n),在交换并重建堆的过程中,需交换n-1次,而重建堆的过程中,根据完全二叉树的性质,[log2(n-1),log2(n-2)...1]逐步递减,近似为nlogn。所以堆排序时间复杂度一般认为就是O(nlogn)级。

  • 相关阅读:
    python——数据库操作
    【笔试】T实习生2014 总结
    【JS】Intermediate6:jQuery
    【JS】Intermediate5:Scope
    【JS】Intermediate4:JSON
    【JS】Intermediate3:AJAX
    【JS】Intermediate2:Events and Callbacks
    【JS】Intermediate1:The DOM
    【JS】Beginner9:Arrays
    【JS】Beginner8:Objects
  • 原文地址:https://www.cnblogs.com/wsl-hitsz/p/14526738.html
Copyright © 2011-2022 走看看