堆排序

作者: 锋芒不露大宝剑 | 来源:发表于2019-04-10 15:29 被阅读0次
    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <string>
    using namespace std;
    
    void print_list(int list[], int len) {
        if (list == NULL || len <= 0) {
            return;
        }
        int line = 0;
        for (int i = 0; i < len; i++, line++) {
            if (line > 9) {
                cout << endl;
                line = 0;
            }
            cout << list[i] << "  ";
        }
        cout << endl;
    }
    
    template<class T>
    void swap_value(T &a, T &b) {
        T tmp = a;
        a = b;
        b = tmp;
    }
    
    /**
        @pragma list    待调整数组
        @pragma index   待调整节点下标
        @pragma len     数组长度
    */
    void HeapAdjust(int *list, int index, int len) {
        // 先保存当前节点下标
        int max = index;
        // 保存左右子节点的数组下标
        int left_child = index * 2 + 1;
        int right_child = index * 2 + 2;
    
        if (left_child < len && list[left_child] > list[max]) {
            max = left_child;
        }
        if (right_child < len && list[right_child] > list[max]) {
            max = right_child;
        }
    
        if (max != index) {
            swap_value(list[max], list[index]);
            HeapAdjust(list, max, len);
        }
    
    }
    
    // 从小到大
    void HeapSort(int list[], int len) {
        if (list == NULL || len <= 0) {
            return;
        }
    
        for (int i = len / 2 - 1; i >= 0; i--) {
            HeapAdjust(list, i, len);
        }
        // 交换堆顶元素与最后一个元素
        for (int i = len - 1; i >= 0; i--) {
            swap_value(list[0], list[i]);
            HeapAdjust(list, 0, i);
        }
    }
    
    int main(int argc, char* argv[]) {
    
        int list[] = {4, 2, 8, 0, 5, 7, 1, 3, 9};
        int len = sizeof(list) / sizeof(*list);
    
        print_list(list, len);
        HeapSort(list, len);
        print_list(list, len);
    
        cout << endl;
        return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:堆排序

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