Heap Sort in C++

本文详细介绍了一种高效的排序算法——堆排序。首先介绍了堆的基本概念及其性质,并解释了如何通过maxHeapify函数来维护最大堆的特性。接着,文章阐述了如何构建最大堆,并在此基础上实现堆排序算法。此外,还提供了递归和迭代两种实现方式的对比。
/*
This function is an important subroutine for manipulating max-heaps. Its inputs are an array A with it's length and an index i into the array.

When maxHeapify is called, it is assumed that the binary trees rooted at it's children are max-heaps, but that A[i] may be smaller than its children, thus violating the max-heap property. The function is to let the value at A[i] "float down" in the max-heap so that the subtree rooted at index i becomes a max-heap.
*/
void maxHeapify(int A[], int length, int i) {
    int left = 2 * i;
    int right = 2 * i + 1;
    int largest = i;
   
    if (left < length && A[left] > A[largest]) {
        largest = left;
    }
   
    if (right < length && A[right] > A[largest]) {
        largest = right;
    }
   
    if (largest != i) {
        int temp = A[i];
        A[i] = A[largest];
        A[largest] = temp;
        maxHeapify(A, length, largest);
    }
}

/*
The recursive version of maxHeapify above might cause some compilers to produce inefficient code. Below is an iterative version.
*/
void maxHeapifyInLoop(int A[], int length, int i) {
    int cur = i;
    int left;
    int right;
    int largest;
    int temp;

    while (cur < length) {
        left = 2 * cur;
        right = 2 * cur + 1;
        largest = cur;
       
        if (left < length && A[left] > A[largest]) {
            largest = left;
        }
   
        if (right < length && A[right] > A[largest]) {
            largest = right;
        }
       
        if (largest == cur) break;
       
        // switch A[cur] and A[largest]
        temp = A[cur];
        A[cur] = A[largest];
        A[largest] = temp;
       
        // change current node to largest
        cur = largest;
    }
}

/*
We can use the procedure "maxHeapify" in a bottom-up manner to convert an array A[0...(n-1)], where n = length[A], into a max-heap. The elements in the subarray A[((n-1)/2+1)...(n-1)] are all leaves of the tree, and so each is a 1-element heap to begin with. The procedure "buildMaxHeap" goes through the remaining nodes of the tree and runs "maxHeapify" on each one.
*/
void buildMaxHeap(int A[], int length) {
    for (int i = (length-1)/2; i >= 0; i--) {
        maxHeapify(A, length, i);
    }
}

/*
The heapsort algorithm starts by using "buildMaxHeap" to build a max-heap on the input array A[0...(n-1)], where n = length[A]. Since the maximum element of the array is stored at the root A[0], it can be put into its correct final position by exchanging it with A[n-1]. If we now "discard" node (n-1) from the heap (by decrementing heap-size[A]), we observe that A[0...(n-2)] can easily be made into a max-heap. The children of the root remain max-heaps, but the new root element may violate the max-heap property. All that is needed to restore the maxheap property, however, is one call to maxHeapify(A, (n-1), 0), which leaves a max-heap in A[0...(n-2)]. The heapsort algorithm then repeats this process for the max-heap of size (n-1)
down to a heap of size 2.
*/
void heapSort(int A[], int length) {
    buildMaxHeap(A, length);
   
    for (int i = length - 1; i > 0; i--) {
        int temp = A[i];
        A[i] = A[0];
        A[0] = temp;
        maxHeapify(A, i, 0);
    }
}
### C++ STL 堆的使用与实现 #### 定义与特性 堆是一种特殊的二叉树结构,在C++标准模板库(STL)中通过`<algorithm>`头文件提供了一系列操作来维护最小堆或最大堆性质的数据容器。这些操作包括但不限于`make_heap`, `push_heap`, `pop_heap`以及`sort_heap`。 #### 函数说明 - **make_heap**: 将指定范围内的元素构造成一个合法的最大/最小堆[^1]。 ```cpp #include <vector> #include <algorithm> int main() { std::vector<int> v = {7, 3, 8, 9, 4}; // 构建最大堆 std::make_heap(v.begin(), v.end()); } ``` - **push_heap**: 向已有的堆中添加新元素并保持其作为堆的有效性. ```cpp // 添加元素至上述构建好的最大堆 v.push_back(10); std::push_heap(v.begin(), v.end()); ``` - **pop_heap**: 移除位于堆顶处的关键字最大的元素(对于最大堆),将其移动到向量末端,再调整剩余部分使之重新成为有效的堆. ```cpp if (!v.empty()) { std::pop_heap(v.begin(), v.end()); // 把最大值移到最后 v.pop_back(); // 删除最后一个元素即原堆顶元素 } ``` - **sort_heap**: 对已经是一个堆的数据集执行排序动作,最终得到升序排列的结果集合. ```cpp // 排序整个堆 std::sort_heap(v.begin(), v.end()); ``` 以上就是关于如何利用STL提供的接口来进行基本的堆管理的方法介绍。值得注意的是,默认情况下所有的堆都是最大堆;如果想要创建最小堆,则需额外传递比较器给相应的函数调用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值