排序算法——堆排序(C++)
生活随笔
收集整理的這篇文章主要介紹了
排序算法——堆排序(C++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
堆排序分為大根堆和小根堆。
堆排思想:(采用樹的概念來組織數據結構,在這里我是根據小根堆對數據進行排序)
①首先我們Insertheap一組數據,在插入的過程中采用向上調整(Shiftup),每次將插入的最小值放在堆頂(heap[0]).
②然后我們Removeheap創建好的堆,將heap[0]節點剔除作為返回值,每次都將最后一個葉子節點賦值到heap[0],然后在執行向下調整(ShiftDown),查找到根節點以下最小的節點,重新創建小跟堆。
#include<iostream> #include<assert.h> using namespace std; #define DEFAULT_SIZE 10 //堆排 class BigHeap { public:BigHeap(int sz = DEFAULT_SIZE){capacity = sz > DEFAULT_SIZE ? sz : DEFAULT_SIZE;heap = new int[capacity];cursize = 0;}~BigHeap(){delete[]heap;heap = NULL;capacity = cursize = 0;} public:void Insert(int& x){if (cursize >= capacity)return;heap[cursize] = x;ShiftUp(cursize);cursize++;}int RemoveHeap(){assert(cursize != 0);int key = heap[0];heap[0] = heap[cursize - 1];cursize--;ShiftDown(0);return key;} public:void ShiftUp(int pos){int i = (pos - 1) / 2;int j = pos;int tmp = heap[j];while (j > 0){if (tmp < heap[i]){heap[j] = heap[i];j = i;i = (j - 1) / 2;}elsebreak;}heap[j] = tmp;}void ShiftDown(int pos){int i = pos;int j = i * 2 + 1; //父的左子樹節點int tmp = heap[i];while (j < cursize){if (j + 1 < cursize && heap[j] > heap[j + 1])j++;if (heap[j] < tmp){heap[i] = heap[j];i = j;j = i * 2 + 1;}elsebreak;}heap[i] = tmp;} private:int* heap;int cursize;int capacity; };void HeapSort(int* a, int n) {BigHeap small(n);for (int i = 0; i < n; i++)small.Insert(a[i]);for (int i = 0; i < n; i++){a[i] = small.RemoveHeap();} } int main() {int arr[] = { 23,12,11,2,5,16,26,37,59,29 };int n = sizeof(arr) / sizeof(int);HeapSort(arr, n);for (int i = 0; i < n; i++){cout << arr[i] << " ";}cout << endl;return 0; }?
轉載于:https://www.cnblogs.com/single-dont/p/11364387.html
總結
以上是生活随笔為你收集整理的排序算法——堆排序(C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker实现运行tomcat并部署项
- 下一篇: C++键盘事件