排序-堆排序

/*
数据交换
*/
void swap(int * a, int * b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

/*
构建大根堆
*/
void PercDown(int * array, int p, int N)
{
    int child, parent;
    int x = array[p];
    for (parent = p; (parent * 2 + 1) < N; parent = child /* 将子节点改成父节点,接着往下判断 */) {
        child = parent * 2 + 1;  // 左孩子节点
        // 获取子节点中的较大值
        // 子节点不是最后一个节点,并且左孩子节点小于右孩子节点,
        if (child != N - 1 && array[child] < array[child + 1]) {
            child++;
        }

        // 如果孩子节点中的较大值都比父节点小,退出
        if (array[child] <= x) {
            break;
        }
        else {
            // 子节点往上移,
            array[parent] = array[child];
        }


    }
    array[parent] = x;
}

/*
堆排序,
*/
void heapSort(int * array, int N)
{
    int i;
    for (i = N / 2 - 1; i >= 0; --i) {
        //创建堆,大根堆
        PercDown(array, i, N);
    }

    for (i = N - 1; i > 0; --i) {
        // 将堆根和堆里面的最后一个元素交换,
        swap(&array[0], &array[i]);
        // 在剩余的堆里面重新创建成大根堆
        PercDown(array, 0, i);
    }
}

参考:网易云课堂:浙江大学-数据结构-陈越、何钦铭