Skip to content

Commit

Permalink
Merge pull request #1117 from Kuljeet-123/heap
Browse files Browse the repository at this point in the history
Heap Sort
  • Loading branch information
Shoaib Rayeen committed Aug 4, 2020
2 parents 21daeb6 + 577b37d commit 4488bdb
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Data Structure/Array Or Vector/Heap Sort/SolutionByKuljeet.cpp
@@ -0,0 +1,50 @@
#include <iostream>
#include<algorithm>
using namespace std;

void maxHeapify(int arr[], int n, int i)
{
int largest = i, left = 2*i+1, right = 2*i+2;
if(left < n && arr[left] > arr[largest])
largest = left;

if(right < n && arr[right] > arr[largest])
largest = right;

if(largest != i)
{
swap(arr[largest],arr[i]);
maxHeapify(arr,n,largest);
}
}

void build(int arr[], int n)
{
for(int i = (n-2)/2;i >= 0;i--)
maxHeapify(arr,n,i);
}

void heapSort(int arr[], int n)
{
build(arr,n);
for(int i = n-1;i >= 1;i--)
{
swap(arr[0],arr[i]);
maxHeapify(arr,i,0);
}


for(int i = 0;i < n;i++)
cout << arr[i] << " ";
}

int main()
{
int n;
cin >> n;
int arr[n];
for(int i = 0;i < n;i++)
cin >> arr[i];
heapSort(arr,n);
return 0;
}
19 changes: 19 additions & 0 deletions Data Structure/Array Or Vector/Heap Sort/readMe.md
@@ -0,0 +1,19 @@
# An unsorted array is given sort the array using heap sort.

# Constraints
- 1 < size Of Array <= 10^6
- 0 < Array Elements <= 10^9

# Input
- Array
- Its Size

# Output
- Print the sorted array.

```
Input : {12, 11, 13, 5, 6, 7}
Output : { 5, 6, 7, 11, 12, 13, }
```

0 comments on commit 4488bdb

Please sign in to comment.