堆——堆排序(C++實現)
阿新 • • 發佈:2019-02-03
堆
堆是一種資料結構;
對於二叉堆,我們可以認為它是一個完全二叉樹;對於一個以陣列的方式儲存的堆的完全二叉樹來說,我們這樣定義一個節點的下標:
parent(i)=i/2;
left(i)=2*i;
right(i)=2*I+1;
二叉堆可以分為兩種形式:最大堆和最小堆;
大根堆:
在大根堆中,要求根節點的值最大,對任意節點有:A[i]≥A[left(i)]&&A[i]≥A[right(i)];即對於大根堆的二叉樹的左右子樹均為大根堆
小根堆
在小根堆中,要求根節點的值最小,對任意節點有:A[i]≤A[left(i)]&&A[i]≤A[right(i)];即對於小根堆的二叉樹的左右子樹均為小根堆
堆排序
堆排序是基於堆的性質實現的;
求降序使用小根堆排序,求升序用大根堆排序
堆排序是一種原址排序,時間複雜度為O(nlgn);
//【大根堆堆排序的實現】 #include "stdafx.h" #include <iostream> using namespace std; int left(int i) { i = 2 * i; return i; } int right(int i) { i = 2 * i+1;return i; } void max_heapify(int * b,int i,int heap_size)//最大堆的維修函式 { int l; int r; int largest; l = left(i); r = right(i); if ((l <= heap_size) && (b[l] > b[i])) largest = l; else largest = i; if ((r <= heap_size) && (b[r] > b[largest])) largest=r; else; if (largest != i) { int temp = b[i]; b[i] = b[largest]; b[largest] = temp; max_heapify(b, largest,heap_size); } else; } //建堆函式 void build_heap( int * a,int arylength) { for(int i=arylength/2;i>0;i--) { max_heapify(a, i,arylength); } } //堆排序 void heap_sort(int * a, int heapsize) { build_heap(a,heapsize); for (int i = heapsize; i>1; i--) { int temp = a[1]; a[1] = a[i]; a[i] = temp; heapsize--; max_heapify(a, 1,heapsize); } } int main() { int length; cout << "please input the length of the array:\n "; cin >> length; int *ary = new int[length+1]; ary[0]=0; cout << "please input the array sequentially:\n"; for (int i = 1; i <= length; i++) {cin >> ary[i];} cout <<endl<< "the array is:" << endl; for (int i = 1; i <= length; i++) { cout << ary[i]<<" "; } build_heap(ary,length); cout <<endl<< "the max_heap is:" << endl; for (int i = 1; i <= length; i++) { cout << ary[i]<<" "; } heap_sort(ary,length); cout <<endl<< "the result is:" << endl; for (int i = 1; i <=length; i++){cout<< ary[i]<<"<=";} return 0; }