File tree 2 files changed +74
-0
lines changed
Searching and Sorting/Heap Sort
2 files changed +74
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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_ */
You can’t perform that action at this time.
0 commit comments