Analysis and implement some simple sorting algorithm.(2)——heapsort
2013-02-19 21:02
399 查看
//modified by quanspace 2013-02-19 20:16
//the time complexity is O(nlgn). # include <iostream> # include <cmath> using namespace std; class heapsort{ public: void print_heap(int a[], int a_size); void max_heapify(int a[], int root, int a_size); void build_max_heap(int a[], int a_size); void int_heapsort(int a[], int a_size); private: int *heap; int heap_size; }; void heapsort::print_heap(int a[], int a_size){ heap = a; heap_size = a_size; for(int i = 0; i != heap_size; ++i){ cout<<*(heap+i)<<" "; } cout<<endl; }
//max_heapify is maintain the heap(big root) property. void heapsort::max_heapify(int a[],int root, int a_size){ int left_child = 2*root; int right_child = 2*root+1; int max = 0; if(left_child<=a_size-1 && a[left_child]>a[root]) max = left_child; else max = root; if(right_child<=a_size-1 && a[right_child]>a[max]) max = right_child; if(max != root){ int temp = a[root]; a[root] = a[max]; a[max] = temp; max_heapify(a, max, a_size); } }
void heapsort::build_max_heap(int a[], int a_size){ heap_size = a_size;
//regardless of the leaves node of tree.
for(int i = floor((heap_size-1)/2); i>=0; --i){ max_heapify(a, i, heap_size); } } void heapsort::int_heapsort(int a[], int a_size){ heap_size = a_size; build_max_heap(a, heap_size); for(int i = heap_size-1; i>=1; --i){ int temp = a[i]; a[i] = a[0]; a[0] = temp; heap_size = heap_size-1; max_heapify(a,0,heap_size); } } int main(){ const int arr_size = 10; int a[arr_size] = {4, 1, 3, 2, 16, 9, 8, 14, 10, 7}; heapsort hs; cout<<"The original heap is: "; hs.print_heap(a, arr_size); hs.int_heapsort(a, arr_size); cout<<"After heap-sort: "; hs.print_heap(a, arr_size); return 0; }
相关文章推荐
- Analysis and implement some simple sorting algorithm.(1)
- implement the bucket sort and some analysis
- [the summarization of algorithm]Heap and Heapsort
- Analysis and implement of Consistent Hashing Algorithm
- Atitit 算法之道 attilax著 1. 第二部分(Part II) 排序与顺序统计(Sorting and Order Statistics) 1 2. 第六章 堆排序(Heapsort)
- 基本数据结构实现(Data Structures and Algorithm Analysis 2rd Edition)
- CLRS: heap sort and priority queue
- Data Structures and algorithm analysis—1.3. A Brief Introduction to Recursion(数据结构—1.3 递归的简介)(之二)
- C code to implement RSA Algorithm(Encryption and Decryption)
- WebSocket(一):Implement Simple Server and Client
- heap sort algorithm 堆排序算法 java实现
- heap and heap sort
- Algorithm: Quick Sort Mind and Related Questions
- Algorithm Analysis of Traffic Interchange and Transportation system
- Heap Data Structure and Heap Sort
- [Algorithms] Heap and Heapsort
- Week1 Assignment - Number Inversion - Stanford - Algorithm: Design and Analysis
- Heapsort algorithm
- 多目标跟踪(MOT)论文随笔-SIMPLE ONLINE AND REALTIME TRACKING (SORT)
- SORT: A Simple, Online and Realtime Tracker