Advertisement
dlackovi2

Heap sort

Dec 9th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void heapsort(int arr[], unsigned int N)
  5. {
  6. unsigned int n = N, i = n/2, parent, child;
  7. int t;
  8.  
  9. for (;;) { /* Loops until arr is sorted */
  10. if (i > 0) { /* First stage - Sorting the heap */
  11. i--; /* Save its index to i */
  12. t = arr[i]; /* Save parent value to t */
  13. } else { /* Second stage - Extracting elements in-place */
  14. n--; /* Make the new heap smaller */
  15. if (n == 0) return; /* When the heap is empty, we are done */
  16. t = arr[n]; /* Save last value (it will be overwritten) */
  17. arr[n] = arr[0]; /* Save largest value at the end of arr */
  18. }
  19.  
  20. parent = i; /* We will start pushing down t from parent */
  21. child = i*2 + 1; /* parent's left child */
  22.  
  23. /* Sift operation - pushing the value of t down the heap */
  24. while (child < n) {
  25. if (child + 1 < n && arr[child + 1] > arr[child]) {
  26. child++; /* Choose the largest child */
  27. }
  28. if (arr[child] > t) { /* If any child is bigger than the parent */
  29. arr[parent] = arr[child]; /* Move the largest child up */
  30. parent = child; /* Move parent pointer to this child */
  31. //child = parent*2-1; /* Find the next child */
  32. child = parent*2+1; /* the previous line is wrong*/
  33. } else {
  34. break; /* t's place is found */
  35. }
  36. }
  37. arr[parent] = t; /* We save t in the heap */
  38. }
  39. }
  40.  
  41. int main(int argc, char* argv[])
  42. {
  43.  
  44. return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement