-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.cpp
More file actions
38 lines (35 loc) · 1.16 KB
/
HeapSort.cpp
File metadata and controls
38 lines (35 loc) · 1.16 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
#include <iostream>
#include "Usefull.h"
#include "HeapSort.h"
void Heapify(int array[], int arraySize, int index) {
int biggest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
// Check if the left child is bigger then the parent
if (left < arraySize && array[left] > array[biggest]) {
biggest = left;
}
// Check if the right child is bigger then the parent
if (right < arraySize && array[right] > array[biggest]) {
biggest = right;
}
// Check if the biggest value is not the parent
if (biggest != index) {
Swap(&array[index], &array[biggest]);
// Call again until achieve the end
Heapify(array, arraySize, biggest);
}
}
void HeapSort(int array[], int arraySize) {
// Build the max heap
for (int index = arraySize/2 - 1; index >= 0; index--) {
Heapify(array, arraySize, index);
}
// One by one extract an element from the max heap
for (int index = arraySize - 1; index >= 0; index--) {
// Move current root to end
Swap(&array[0], &array[index]);
// Call heapify on the reduced heap
Heapify(array, index, 0);
}
}