Skip to content

Commit 3434a87

Browse files
authored
Merge pull request #3 from adithbharadwaj/sorting
added heapsort in sorting algorithms
2 parents 8a2c7af + a979c39 commit 3434a87

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

Algorithms/Sorting/heapSort.cpp

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
2+
// max heap inplementation using arrays without using dynamic resizing.
3+
4+
// best case = worst case = avg case = o(nlogn);
5+
6+
#include<iostream>
7+
8+
#define maxsize 100
9+
10+
using namespace std;
11+
12+
// helper methods
13+
14+
void swap(int *a, int *b){
15+
16+
int temp = *a;
17+
*a = *b;
18+
*b = temp;
19+
20+
}
21+
22+
// function to max_heapify the given array
23+
void max_heapify(int a[], int n, int i){
24+
25+
int max = i;
26+
int l = 2 * i + 1;
27+
int r = 2 * i + 2;
28+
29+
if(l < n && a[l] > a[max]){
30+
max = l;
31+
}
32+
if(r < n && a[r] > a[max]){
33+
max = r;
34+
}
35+
36+
if(max != i){
37+
swap(&a[i], &a[max]);
38+
max_heapify(a, n, max);
39+
}
40+
41+
42+
}
43+
44+
45+
// delete min element and return it
46+
47+
int heapSort(int a[], int n){
48+
49+
for (int i = n/2 - 1; i >= 0; i--){
50+
51+
max_heapify(a, n, i);
52+
53+
}
54+
55+
for (int i = n - 1; i >= 0; i--){
56+
57+
swap(&a[0], &a[i]);
58+
59+
max_heapify(a, i, 0);
60+
61+
}
62+
63+
64+
for (int i = 0; i < n; i++){
65+
66+
cout << a[i] << endl;
67+
68+
}
69+
70+
}
71+
72+
int main(){
73+
74+
int n, el;
75+
76+
cout << "Enter the size of the array: " << endl;
77+
cin >> n;
78+
79+
int a[n];
80+
81+
cout << "Enter the elements" << endl;
82+
83+
for (int i = 0; i < n; i++) {
84+
85+
cin >> a[i];
86+
87+
}
88+
89+
cout << endl;
90+
91+
// heapsort
92+
93+
cout << "The sorted elements are: " << endl;
94+
95+
heapSort(a, n);
96+
97+
return 0;
98+
99+
}

0 commit comments

Comments
 (0)