Algorithmic Implementation series(5) Implementation of Heap_Sort

来源:互联网 发布:sql upper 编辑:程序博客网 时间:2024/05/16 16:56

compiler: gcc 4.7.3

C++0X

OS: centos 6.3 x86

  1 #include <iostream>                                                                                 

  2 
  3 using namespace std;
  4 
  5 //Getting the subscript of the left child of element i
  6 const size_t left(const size_t i) {
  7     return i * 2;
  8 }
  9 
 10 //Getting the subscript of the right child of element i
 11 const size_t right(const size_t i) {
 12     return i * 2 + 1;
 13 }
 14 
 15 //Getting the subscript of the parent of element i
 16 const size_t parent(const size_t i) {
 17     return i / 2;
 18 }
 19 
 20 //swap the ith element and the jth element in an array
 21 void swap_elements(int ia[], const size_t i, const size_t j) {
 22     const int tmp = ia[i - 1];
 23     ia[i - 1] = ia[j - 1];
 24     ia[j - 1] = tmp;
 25 }
 26                                                                                                     
 27 void Max_Heapify(int ia[], const size_t i, 
 28                 const size_t heap_size) {
 29     const size_t l = left(i);
 30     const size_t r = right(i); 
 31     
 32     //Storing the subscript of the one among element i and its left 
 33     //and right child, the value of which is the largest.
 34     size_t largest = i;
 35     
 36     if(l <= heap_size && ia[l - 1] > ia[i - 1]) {
 37         largest = l;
 38     }
 39     
 40     if(r <= heap_size && ia[r -1] > ia[largest -1]) {
 41         largest = r;
 42     }
 43 
 44     if(largest != i) {
 45         swap_elements(ia, i, largest);
 46         Max_Heapify(ia, largest, heap_size);
 47     }
 48 }   
 49 
 50 void Build_Max_Heap(int ia[], const size_t size) {
 51     const size_t heap_size = size;
 52     for(size_t i = size / 2; i != 0; --i) {
 53         Max_Heapify(ia, i, heap_size);
 54     }
 55 }
 56 
 57 void Heap_Sort(int ia[], const size_t size) {
 58     Build_Max_Heap(ia, size);
 59 
 60     size_t heap_size = size;
 61 
 62     for(size_t i = size; i > 1; --i) {
 63         swap_elements(ia, 1, i);
 64         --heap_size;
 65         Max_Heapify(ia, 1, heap_size);
 66     }
 67 }
 68                 
 69     
 70 int main() {
 71     int ia[] = {3, 2, 4, -3, -22, 12, 43, -55, 66, -65, 99};
 72     int *pa = &ia[0];
 73 
 74     Heap_Sort(pa, sizeof(ia)/sizeof(int));
 75 
 76     for(size_t i = 0; i != sizeof(ia)/sizeof(int); ++i) {
 77         cout << ia[i] << " ";
 78     }
 79     cout << endl;
 80 
 81     return EXIT_SUCCESS;
 82 }