Advertisement
myLoveOnlyForYou

Untitled

Jun 7th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void heapBottom(int *a, int begin, int end) {
  5. int now = begin;
  6. int left = begin * 2 + 1;
  7. while (left <= end) {
  8. if (left < end && a[left] < a[left + 1]) {
  9. left++;
  10. }
  11. if (a[now] < a[left]) {
  12. swap(a[left], a[now]);
  13. now = left;
  14. left = 2 * left + 1;
  15. }
  16. else {
  17. break;
  18. }
  19. }
  20. }
  21.  
  22. void heapSort(int *a, int n) {
  23. for (int i = n / 2; i >= 0; i--) {
  24. heapBottom(a, i, n - 1);
  25. }
  26. for (int i = n - 1; i >= 1; i--) {
  27. swap(a[0], a[i]);
  28. heapBottom(a, 0, i - 1);
  29. }
  30. }
  31. int main()
  32. {
  33. freopen("input.txt", "r", stdin);
  34. freopen("output.txt", "w", stdout);
  35. int n; cin >> n;
  36. int *a = new int[n];
  37. for (int i = 0; i < n; i++) {
  38. cin >> a[i];
  39. }
  40. heapSort(a, n);
  41. for (int i = 0; i < n; i++) {
  42. cout << a[i] << " ";
  43. }
  44. return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement