Heap sort is divided into a large heap roots and rootlets heap.
:( heap row concept idea to organize data using a tree structure, where I was based on a small root heap sort the data)
① First we Insertheap a set of data, used during insertion adjusted upward (Shiftup), each inserted on top of the stack of the minimum value (heap [0]).
② Then we Removeheap create good heap, the heap [0] nodes are taken out as a return value, each time the last leaf node assigned to heap [0], then the implementation of downward adjustment (shiftDown) , find the root of the following the smallest node, re-created with a small heap.
#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; } else break; } 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; } else break; } 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; }