From fa4e2f22a0c55fac8cd82a1f105cc2aededa3307 Mon Sep 17 00:00:00 2001 From: Ayushi C <67193440+AyushiChakrabarty@users.noreply.github.com> Date: Wed, 4 Nov 2020 09:54:25 +0530 Subject: [PATCH] Create Heap Data Structure --- Heap Data Structure | 111 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 Heap Data Structure diff --git a/Heap Data Structure b/Heap Data Structure new file mode 100644 index 0000000..5e352d5 --- /dev/null +++ b/Heap Data Structure @@ -0,0 +1,111 @@ +//HEAPS +#include +using namespace std; + + +//function to check whether given set of arrays is a max heap or not +int check_heap(int c[],int count, int n) +{ + if( count>(n-2)/2) + return 1; + + if(c[count]>=c[2*count + 2] && c[count]>=c[2*count +1] && check_heap(c, 2*count + 2, n) && check_heap(c, 2* count +1,n)) + return 1; + + return 0; +} + + +void heapify(int arr[], int n, int i) +{ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + swap(arr[i], arr[largest]); + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } +} + + +void heapSort(int arr[], int n) +{ + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i=n-1; i>0; i--) + { + // Move current root to end + swap(arr[0], arr[i]); + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } +} + +/* A utility function to print array of size n */ +void printArray(int arr[], int n) +{ + for (int i=0; i