Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

heap_sort.cpp: Adds Heap Sort Algorithm #107

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ This repository contains examples of various algorithms written on different pro
| [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | | | [:octocat:](radix_sort/Python) |
| [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | | | [:octocat:](binary_search/Python) |
| [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | | [:octocat:](bubble_sort/C++) | | |

| [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) | | [:octocat:](heap_sort/C++) | | |

## Implemented Data Structures

Expand Down
60 changes: 60 additions & 0 deletions heap_sort/C++/heap_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#include <iostream>

using namespace std;

void heapify(int input[], int n, int i)
{

int largest = i; // Assign the largest as root
int left = 2*i + 1; // Calculate the index of left element
int right = 2*i + 2; // Calculate the index of right element

//Checking if the left is larger than current large value
if (left < n && input[left] > input[largest])
largest = left;

//Checking if the right is larger than current large value
if (right < n && input[right] > input[largest])
largest = right;

if (largest != i)
{
swap(input[i], input[largest]);

heapify(input, n, largest);
}
}

void heapSort(int input[], int n)
{ // Function to perform heap sort.

// Building the heap, effectively rearranging the array.
for (int i = n / 2 - 1; i >= 0; i--)
heapify(input, n, i);

for (int i=n-1; i>=0; i--)
{
swap(input[0], input[i]);
heapify(input, i, 0);
}
}

int main()
{
int n;
cout<<"Enter the number of elements"<<endl;
cin>>n;
int array[n];
cout<<"Enter the elements of array"<<endl;

for(int i=0; i<n; i++){
cin>>array[i];
}
heapSort(array, n);
cout << "Sorted array is \n";
for(int i=0; i<n; i++){
cout<<array[i]<<" ";
}
cout<<endl;
return 1;
}