HeapSort Algorithm Source Code in C++


SUBMITTED BY: Guest

DATE: Nov. 12, 2013, 2:51 a.m.

FORMAT: Text only

SIZE: 1.7 kB

HITS: 1043

  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. using namespace std;
  10. void heapsort(int array[], int size);
  11. void buildheap(int array[], int size);
  12. void percolateDown(int heap[], int size, int id);
  13. void printArray(int array[], int size) {
  14. for(int i=0; i<size; i++) {
  15. cout << array[i] << " ";
  16. }
  17. cout << endl;
  18. }
  19. int main() {
  20. int size = 20;
  21. int arrayToSort[size];
  22. for(int i=0; i<size; i++)
  23. arrayToSort[i] = 1+rand()%99; // between 1 and 99
  24. printArray(arrayToSort, size);
  25. heapsort(arrayToSort, size);
  26. printArray(arrayToSort, size);
  27. }
  28. void heapsort(int array[], int size) {
  29. buildheap(array, size);
  30. int heapsize = size;
  31. for(int i=size-1; i>0; i--) {
  32. int temp = array[i];
  33. array[i] = array[0];
  34. array[0] = temp;
  35. heapsize--;
  36. percolateDown(array, heapsize, 0);
  37. }
  38. }
  39. void buildheap(int array[], int size) {
  40. for(int i=size/2; i>=0; i--) {
  41. percolateDown(array, size, i);
  42. }
  43. }
  44. void percolateDown(int array[], int size, int id) {
  45. int current = id;
  46. int max;
  47. while(true) {
  48. int left = current*2+1;
  49. int right = current*2+2;
  50. if(left >= size)
  51. return;
  52. else if(right >= size)
  53. max = left;
  54. else if(array[left] > array[right])
  55. max = left;
  56. else if(array[left] < array[right])
  57. max = right;
  58. if(array[max] > array[current]) {
  59. int temp = array[max];
  60. array[max] = array[current];
  61. array[current] = temp;
  62. current = max;
  63. } else
  64. return;
  65. }
  66. }

comments powered by Disqus