Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1117 from Kuljeet-123/heap
Heap Sort
- Loading branch information
Showing
2 changed files
with
69 additions
and
0 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
Data Structure/Array Or Vector/Heap Sort/SolutionByKuljeet.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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, } | ||
``` | ||
|