Skip to content

Commit 36694f7

Browse files
authored
Merge pull request #741 from nlok5923/heapsort
Added heap_sort [C++]
2 parents 99ef5f1 + f42ef41 commit 36694f7

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

heap_sort/heapsort.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void swap(int array[], int index1, int index2) //swapping function wihout using third variable
5+
{
6+
array[index1] = array[index1] + array[index2];
7+
array[index2] = array[index1] - array[index2];
8+
array[index1] = array[index1] - array[index2];
9+
}
10+
void heapify(int array[], int size, int index)
11+
{
12+
int largest = index; //considering largest as root
13+
int left = 2 * index + 1;
14+
int right = 2 * index + 2;
15+
16+
if (left < size && array[left] > array[largest]) //left child is larger then root
17+
largest = left;
18+
19+
if (right < size && array[right] > array[largest]) //right child is larger then root
20+
largest = right;
21+
22+
if (largest != index) //condition if largest is not root
23+
{
24+
swap(array, index, largest);
25+
heapify(array, size, largest);
26+
}
27+
}
28+
void heapsort(int array[], int size)
29+
{
30+
31+
for (int i = size / 2 - 1; i >= 0; i--) //Create heap from array rearrangement
32+
heapify(array, size, i);
33+
34+
for (int i = size - 1; i > 0; i--) //move current root to end a step for Extract min process
35+
{
36+
37+
swap(array, 0, i); //swap element
38+
39+
heapify(array, i, 0); //excecuting heapify to bring all elements in correct position again
40+
}
41+
}
42+
void display(int array[], int size)
43+
{
44+
int i = 0;
45+
for (i = 0; i < size; i++)
46+
cout << array[i] << " ";
47+
cout << endl;
48+
}
49+
int main()
50+
{
51+
int array[] = {6, 3, 6, 343, 42, 1, 43, 35, 34, 43};
52+
int size = sizeof(array) / sizeof(array[0]);
53+
cout << "Unsorted array is :" << endl;
54+
display(array, size); //display the unsorted array
55+
heapsort(array, size);
56+
cout << "sorted array is :" << endl;
57+
display(array, size); //display the sorted array
58+
}

0 commit comments

Comments
 (0)