From c454255604f8769db43a98e7870c0fde4eec6b05 Mon Sep 17 00:00:00 2001 From: Divya Gupta <38471510+divya144@users.noreply.github.com> Date: Tue, 2 Oct 2018 22:56:20 +0530 Subject: [PATCH] Heap sort algorithm This sorting algorithm sorts an array in ascending order in O(nlogn) time. --- sorting/heap_sort.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 sorting/heap_sort.cpp diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp new file mode 100644 index 00000000..6b61fd17 --- /dev/null +++ b/sorting/heap_sort.cpp @@ -0,0 +1,55 @@ +/* +C++ implementation of heap sort +Author:Divya Gupta +Input:An array of integers +Output: Gives an array sorted in ascending order +Time Complexity:O(nlogn) +*/ +#include +using namespace std; +void swap(int* num1, int* num2) +{ + int temp = *num1; + *num1 = *num2; + *num2 = temp; +} +void heapify(int A[], int high, int low) +{ + int r = 2*low + 2; + int largest = low; + int l = 2*low + 1; + if (l < high && A[l] > A[largest]) + largest = l; + if (r < high && A[r] > A[largest]) + largest = r; + if (largest != low) + { + swap(&A[low],&A[largest]); + heapify(A, high, largest); + } +} +void heapSort(int A[], int low, int high) +{ + for (int i = high / 2 - 1; i >= 0; i--) + heapify(A, high, i); + for (int i=high-1; i>=0; i--) + { + swap(&A[0],&A[i]); + heapify(A, i, 0); + } +} + +int main() +{ + cout<<"Enter number of elements in an array"<>n; + int a[n]; + for(int i=0;i>a[i]; + heapSort(a,0,n); + cout<<"Sorted array"<