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
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h>
#define SWAP(a, b) do { int temp = a; a = b; b = temp; } while(0)
void heapify(int arr[], int start, int end) { int parent = start; int child = 2 * parent + 1; while (child <= end) { if (child + 1 <= end && arr[child] < arr[child + 1]) { child++; } if (arr[parent] >= arr[child]) { break; } SWAP(arr[parent], arr[child]); parent = child; child = 2 * parent + 1; } }
void heap_sort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, i, n - 1); } for (int i = n - 1; i > 0; i--) { SWAP(arr[0], arr[i]); heapify(arr, 0, i - 1); } }
void heapify_up(int arr[], int index) { while (index > 0) { int parent = (index - 1) / 2; if (arr[index] <= arr[parent]) { break; } SWAP(arr[index], arr[parent]); index = parent; } }
void heap_insert(int arr[], int* size, int value) { arr[*size] = value; heapify_up(arr, *size); (*size)++; }
int heap_extract_max(int arr[], int* size) { if (*size <= 0) return -1; int max_value = arr[0]; arr[0] = arr[*size - 1]; (*size)--; if (*size > 0) { heapify(arr, 0, *size - 1); } return max_value; }
|