1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| #include <iostream> using namespace std;
void swap(int &a, int &b) { int temp = a; a = b; b = temp; }
void heapInsert1(int arr[], int i) { while (arr[i] > arr[(i - 1) / 2]) { swap(arr[i], arr[(i - 1) / 2]); i = (i - 1) / 2; } }
void heapInsert2(int arr[], int i, int n) { while ((arr[i] < arr[i * 2 + 1] || arr[i] < arr[i * 2 + 2]) && (i * 2 + 1 < n && i * 2 + 2 < n)) { int best = i; if (arr[i * 2 + 2] < arr[i * 2 + 1]) { best = i * 2 + 1; } else { best = i * 2 + 2; } swap(arr[i], arr[best]); i = best; } }
void heapify(int arr[], int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) largest = left;
if (right < n && arr[right] > arr[largest]) largest = right;
if (largest != i) { swap(arr[i], arr[largest]);
heapify(arr, n, largest); } }
void heapsort1(int arr[], int n) { for (int i = 0; i < n; i++) { heapInsert1(arr, i); } int size = n; while (size > 1) { swap(arr[0], arr[--size]); heapify(arr, size, 0); } }
void heapsort2(int arr[], int n) { for (int i = n - 1; i >= 0; i--) { heapInsert2(arr, i, n); } int size = n; while (size > 1) { swap(arr[0], arr[--size]); heapify(arr, size, 0); } }
int main() { int n; cin >> n; int arr1[n], arr2[n]; for (int i = 0; i < n; i++) { cin >> arr1[i]; arr2[i] = arr1[i]; } heapsort1(arr1, n); for (int i = 0; i < n; i++) { cout << arr1[i] << " "; } cout << endl; heapsort2(arr2, n); for (int i = 0; i < n; i++) { cout << arr2[i] << " "; } }
|