Advertisement
sedran

HeapSort Algorithm Source Code in C++

Dec 13th, 2011
3,967
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. /*
  2.  * HeapSort.cpp
  3.  *
  4.  *  Created on: 13 Ara 2011
  5.  *      Author: blog.asosyalbebe.com
  6.  */
  7. #include <iostream>
  8. #include <stdlib.h>
  9.  
  10. using namespace std;
  11.  
  12. void heapsort(int array[], int size);
  13. void buildheap(int array[], int size);
  14. void percolateDown(int heap[], int size, int id);
  15.  
  16. void printArray(int array[], int size) {
  17.     for(int i=0; i<size; i++) {
  18.         cout << array[i] << " ";
  19.     }
  20.     cout << endl;
  21. }
  22.  
  23. int main() {
  24.     int size = 20;
  25.     int arrayToSort[size];
  26.     for(int i=0; i<size; i++)
  27.         arrayToSort[i] = 1+rand()%99; // between 1 and 99
  28.     printArray(arrayToSort, size);
  29.  
  30.     heapsort(arrayToSort, size);
  31.  
  32.     printArray(arrayToSort, size);
  33. }
  34.  
  35. void heapsort(int array[], int size) {
  36.     buildheap(array, size);
  37.     int heapsize = size;
  38.  
  39.     for(int i=size-1; i>0; i--) {
  40.         int temp = array[i];
  41.         array[i] = array[0];
  42.         array[0] = temp;
  43.         heapsize--;
  44.         percolateDown(array, heapsize, 0);
  45.     }
  46. }
  47.  
  48. void buildheap(int array[], int size) {
  49.     for(int i=size/2; i>=0; i--) {
  50.         percolateDown(array, size, i);
  51.     }
  52. }
  53.  
  54. void percolateDown(int array[], int size, int id) {
  55.     int current = id;
  56.     int max;
  57.     while(true) {
  58.         int left = current*2+1;
  59.         int right = current*2+2;
  60.         if(left >= size)
  61.             return;
  62.         else if(right >= size)
  63.             max = left;
  64.         else if(array[left] > array[right])
  65.             max = left;
  66.         else if(array[left] < array[right])
  67.             max = right;
  68.         if(array[max] > array[current]) {
  69.             int temp = array[max];
  70.             array[max] = array[current];
  71.             array[current] = temp;
  72.             current = max;
  73.         } else
  74.             return;
  75.     }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement