c++堆详解【附代码】

目录

引言

一、堆的概念

二、堆的实现方式

三、堆的常见操作

四、堆的实现代码

结论

参考资料


引言

在计算机科学中,堆(Heap)是一种常见的数据结构,用于动态分配内存和管理数据。堆具有高效的插入和删除操作,并广泛应用于各种算法和数据结构中。本文将详细介绍堆的概念、原理、实现方式以及在C++中的应用,并提供相关的代码示例。

一、堆的概念

堆是一种特殊的树状数据结构,它满足以下两个条件:

  1. 堆是一个完全二叉树(Complete Binary Tree),即除了最后一层外,其他层的节点数都是满的,并且最后一层的节点都尽量靠左排列。
  2. 对于每个节点,它的值必须大于等于(或小于等于)其子节点的值。这种性质被称为堆属性(Heap Property)。

根据堆属性的不同,我们可以将堆分为最大堆和最小堆。在最大堆中,父节点的值大于等于其子节点的值;而在最小堆中,父节点的值小于等于其子节点的值。

二、堆的实现方式

堆可以使用数组或链表来实现。在本文中,我们将重点介绍使用数组实现堆的方法。

使用数组实现堆时,我们可以通过简单的数学关系来计算节点之间的父子关系,如下:

  1. 对于索引为 i 的节点,其左子节点的索引为 2i+1,右子节点的索引为 2i+2。
  2. 对于索引为 i 的节点,其父节点的索引为 (i-1)/2。

三、堆的常见操作

  1. 插入元素:将新元素添加到堆的末尾,并根据堆属性进行调整。这通常涉及到通过交换节点来移动新元素,直到满足堆属性为止。插入元素的时间复杂度为 O(log n),其中 n 是堆中元素的个数。
  2. 删除堆顶元素:将堆顶元素删除,并将最后一个元素放在堆顶,然后根据堆属性进行调整。这通常涉及到通过交换节点来移动元素,直到满足堆属性为止。删除堆顶元素的时间复杂度为 O(log n)。
  3. 获取堆顶元素:直接返回堆顶的元素,时间复杂度为 O(1)。
  4. 堆排序:通过不断删除堆顶元素并将其放入结果中来对堆进行排序。堆排序的时间复杂度为 O(n log n),其中 n 是堆中元素的个数。

四、堆的实现代码

下面是使用C++实现堆的示例代码:

#include <iostream>
#include <vector>

class Heap {
private:
    std::vector<int> heap;

    void heapifyUp(int index) {
        if (index == 0) {
            return;
        }

        int parentIndex = (index - 1) / 2;
        if (heap[parentIndex] < heap[index]) {
            std::swap(heap[parentIndex], heap[index]);
            heapifyUp(parentIndex);
        }
    }

    void heapifyDown(int index) {
        int leftChildIndex = 2 * index + 1;
        int rightChildIndex = 2 * index + 2;
        int largestIndex = index;

        if (leftChildIndex < heap.size() && heap[leftChildIndex] > heap[largestIndex]) {
            largestIndex = leftChildIndex;
        }

        if (rightChildIndex < heap.size() && heap[rightChildIndex] > heap[largestIndex]) {
            largestIndex = rightChildIndex;
        }

        if (largestIndex != index) {
            std::swap(heap[index], heap[largestIndex]);
            heapifyDown(largestIndex);
        }
    }

public:
    void insert(int value) {
        heap.push_back(value);
        heapifyUp(heap.size() - 1);
    }

    void remove() {
        if (heap.empty()) {
            return;
        }

        std::swap(heap[0], heap[heap.size() - 1]);
        heap.pop_back();
        heapifyDown(0);
    }

    int top() {
        if (heap.empty()) {
            throw std::runtime_error("Heap is empty");
        }

        return heap[0];
    }
};

int main() {
    Heap maxHeap;

    maxHeap.insert(5);
    maxHeap.insert(10);
    maxHeap.insert(3);

    std::cout << "Top element: " << maxHeap.top() << std::endl;

    maxHeap.remove();

    std::cout << "Top element after removal: " << maxHeap.top() << std::endl;

    return 0;
}

以上代码将输出:

Top element: 10
Top element after removal: 5

结论

堆是一种重要的数据结构,它具有高效的插入和删除操作,并广泛应用于各种算法和数据结构中。最大堆和最小堆是堆的两种常见类型,它们可以使用数组实现。通过堆,我们可以轻松地获取最大或最小的元素,并且堆排序是一种高效的排序算法。掌握堆的概念、实现方式以及相关操作,在解决问题时将会事半功倍。

参考资料

  • Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. "Introduction to Algorithms." MIT Press, 2009.
  • Sedgewick, R., & Wayne, K. "Algorithms." Addison-Wesley Professional, 2011.
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是排序的C++代码: ```c++ #include <iostream> using namespace std; void heapify(int arr[], int n, int i) { int largest = i; int l = 2*i + 1; int r = 2*i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); } } void heapSort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i=n-1; i>=0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } } void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n"; } int main() { int arr[] = {12, 11, 13, 5, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Original array: "; printArray(arr, n); heapSort(arr, n); cout << "Sorted array: "; printArray(arr, n); } ``` 这段代码中包含了两个函数:`heapify` 和 `heapSort`。 `heapify` 函数将给定的数组中的元素进行化,即将元素按照一定规则构建成最大或最小。这里使用的是构建最大的方式。`heapify` 函数的时间复杂度为 O(log n)。 `heapSort` 函数则是排序的主要实现。首先,它将给定的数组进行化,然后将顶元素(即最大值或最小值)与底元素进行交换,并将大小减 1。接着,它再次对进行化,重复上述步骤直至为空。`heapSort` 函数的时间复杂度为 O(n log n)。 最后,`printArray` 函数用于打印排序后的数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪子小院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值