-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapsorto.h
More file actions
45 lines (35 loc) · 1.14 KB
/
Copy pathheapsorto.h
File metadata and controls
45 lines (35 loc) · 1.14 KB
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
void swap(int *a, int *b);
void heapifyo(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
int c = l < n && arr[l] > arr[largest];
largest = c ? l : largest;
// If right child is larger than largest so far
c = r < n && arr[r] > arr[largest];
largest = c ? r : largest;
// If largest is not root
if (largest != i) {
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected sub-tree
heapifyo(arr, n, largest);
}
}
int count = 0;
void heapsorto_h(int array[], int n) {
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapifyo(array, n, i);
// One by one extract an element from heap
count++;
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
swap(&array[0], &array[i]);
// call max heapify on the reduced heap
heapifyo(array, i, 0);
}
}
void heapsorto(int array[], int low, int high) {
heapsorto_h(&array[low], high - low + 1);
}