diff --git a/All Other Program/Heap_Sort.cpp b/All Other Program/Heap_Sort.cpp new file mode 100644 index 0000000..c4e5143 --- /dev/null +++ b/All Other Program/Heap_Sort.cpp @@ -0,0 +1,75 @@ +/* +Heap Sort arranges an array in a binary tree, Make it a Max Heap and then store larger values from end to make a sorted array. +*/ + +#include +using namespace std; + +// heapify function to swap values to make a max heap binary tree (Tree in which the root element will be larger than child nodes). +void heapify(int ar[],int n,int i){ + int largest=i; + // Left and right child of tree when arranged as tree from array + int left=2*i+1; + int right=2*i+2; + if(ar[left]>ar[largest] && leftar[largest] && right=0;--i){ + heapify(ar,n,i); + } + + // Swap 0th element to last element as 0th will be largest value according to max heap tree and run heapify again except on swapped element, Hence array will be sorted. + for(int i=n-1;i>=0;--i){ + swap(ar[0],ar[i]); + heapify(ar,i,0); + } +} + +//Sorting Algorithm Boiler code to take input of array, call the sorting function and print the array. +int main(){ + cout<<"Enter size of array : "; + int size; + cin>>size; + int ar[size]; + for(int i=0;i>ar[i]; + } + cout<<"Before Sort : "<