Skip to content

Commit dd377c4

Browse files
Merge pull request #387 from ahmibr/heap_sort
Add heap sort
2 parents a6f3c2c + 09d042e commit dd377c4

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include "HeapSort.h"
2+
#include <algorithm>
3+
4+
HeapSort::HeapSort() {
5+
heapSize = 0;
6+
}
7+
8+
HeapSort::~HeapSort() {};
9+
void HeapSort::sort(int* arr, int size) {
10+
11+
buildMaxHeap(arr, size);
12+
for (int i = size - 1; i > 0; --i) {
13+
//arr[0] is the largest element in heap, put it in the end
14+
std::swap(arr[0], arr[i]);
15+
16+
//heap size is decreased after removing an element
17+
--heapSize;
18+
19+
//heap is corrupted now, fix it
20+
maxHeapify(arr, 0);
21+
}
22+
23+
}
24+
25+
void HeapSort::maxHeapify(int* arr, int idx) {
26+
27+
while (1) {
28+
int left = LEFT(idx);
29+
int right = RIGHT(idx);
30+
31+
int largestIdx = idx;
32+
33+
//get max element from me,my left child, my right child
34+
if (left < heapSize && arr[left] > arr[largestIdx])
35+
largestIdx = left;
36+
37+
if (right < heapSize && arr[right] > arr[largestIdx])
38+
largestIdx = right;
39+
40+
if (largestIdx == idx) //now it remains heap property
41+
break;
42+
43+
//arr[largestIdx] now contains the smaller element to be pushed down
44+
std::swap(arr[idx], arr[largestIdx]);
45+
idx = largestIdx;
46+
}
47+
}
48+
49+
void HeapSort::buildMaxHeap(int* arr, int size) {
50+
heapSize = size;
51+
for (int i = ((size) >> 1) - 1; i >= 0; --i)
52+
maxHeapify(arr, i);
53+
}
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#ifndef HEAPSORT_HEAPSORT_H_
2+
#define HEAPSORT_HEAPSORT_H_
3+
4+
//Helper macros to access left,right child and parent
5+
#define RIGHT(i) ((i<<1)+2)
6+
#define LEFT(i) ((i<<1)+1)
7+
#define PARENT(i) ((i-1)>>1)
8+
9+
class HeapSort:{
10+
11+
private:
12+
int heapSize;
13+
void maxHeapify(int* arr, int idx);
14+
void buildMaxHeap(int* arr, int size);
15+
public:
16+
HeapSort();
17+
virtual void sort(int* arr, int size);
18+
virtual ~HeapSort();
19+
};
20+
21+
#endif /* HEAPSORT_HEAPSORT_H_ */

0 commit comments

Comments
 (0)