堆排序

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
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
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;
}

你可能感兴趣的:(堆排序)