MaxHeap.cpp 936 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // Created by tangs on 2018/11/19.
  3. //
  4. #include <iostream>
  5. using namespace std;
  6. void AdjustDown(int A[], int k , int len) {
  7. A[0] = A[k];
  8. int i;
  9. for (i = 2 * k; i <= len; i *= 2) {
  10. if (i < len && A[i] < A[i + 1]) {
  11. i++;
  12. }
  13. if (A[0] >= A[i]) {
  14. break;
  15. } else {
  16. A[k] = A[i];
  17. k = i;
  18. }
  19. }
  20. A[k] = A[0];
  21. }
  22. void BuildMaxHeap(int A[], int len) {
  23. for (int i = len / 2; i > 0; i--) {
  24. AdjustDown(A, i, len);
  25. }
  26. }
  27. void MaxHeapSort(int A[], int len) {
  28. BuildMaxHeap(A, len);
  29. int i;
  30. for (i = len; i > 1; i--) {
  31. swap(A[i], A[1]);
  32. AdjustDown(A, 1, i - 1);
  33. }
  34. }
  35. int main(){
  36. int A1[] = {6, 1, 5, 2, 1, 9, 10, 24, 7, 0};
  37. MaxHeapSort(A1, 9);
  38. // print:
  39. // 0 0 1 1 2 5 7 9 10 24
  40. for (int i = 0; i < 10; i++) {
  41. cout << A1[i] << " ";
  42. }
  43. cout << endl;
  44. return 0;
  45. }