From 76fb23738c46cd6bb21aade818b86112d31adc40 Mon Sep 17 00:00:00 2001 From: Antew Date: Thu, 11 Oct 2018 20:28:52 +0530 Subject: [PATCH] added heapsort in cpp --- Sorting/Heap Sort/cpp/a.out | Bin 0 -> 13344 bytes Sorting/Heap Sort/cpp/heapsort.cpp | 68 +++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100755 Sorting/Heap Sort/cpp/a.out create mode 100644 Sorting/Heap Sort/cpp/heapsort.cpp diff --git a/Sorting/Heap Sort/cpp/a.out b/Sorting/Heap Sort/cpp/a.out new file mode 100755 index 0000000000000000000000000000000000000000..1200f2ff65a003c9dc5113d154f78dd8acb0a182 GIT binary patch literal 13344 zcmeHOeQ;b=6~CM9M}T&_g%)Bd_7z)gDP58_O;c(io8+}`YtqIhL4=maW_Qy(o9t$G z-G|nzI^Vn)`cFNi$ zaPU^UI}>TOtEysM(X?r&qn4eC#B_ZRu#IqH#mrR3PA8&0kyx9lw{9|9J{E(&R=YZu z%G%O%sym}w0^^DCP%w(v0W;Qh!0e1#-56V}FKR~ZM4tr<$#h!DXt#AY24j+;8h20B zN{Ss#k@|*PZ#6fDs-3#I!ByK3+Jx|x;h!Jt+%MO#v#y=G537_y%=2fjeHdGUUo2B` z_rdaIC8v2<%-fvvE`YDk3hzn<5Bp7qy7(k(%cj1>7P$9-$xazu;@;aqGo}YCR zJgM}lFT9Tse!_(pwr=1*bm6>5lKzkjcmIyO=)&FmsL}s=xsjjyOob+l`-kkZ$6^ij!dGg-bp-#_UviN*Aq`eI6EZy8;Pf`pFJV@ z4a8HI&mNcjb>KS(!OK$hMkM$09Y*etM*ryfmbRvWxvxUk7+4sSWZNI$d2;DI*j!k& zqLC!q)`Dp_2Ij5=HMWc!x!3FuU`VfCP*qw>@Ypg;WxoAFzIl}Tnfp0m z^D*$jmri-cp4Ufn&pmr?h41vsI}*K;yBPEQ80eDlo{ggixYbNcdW>21RI=O0h+(Xc*2ittNu+fu^+>Ac9j zfYtS-rI_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g zsPK7-^Yy*)Vtb~)gbf|-*q-nG9=wLUO|3VFo8sC24-nAWV|zaD^Z$q72ZPrq+i}0> z{6j-5*sFWL!4&{edL2^uW_zaRAaUCl&J&tr!tJmFwqyQ0Dui+Snx;un&>^CNoV$wV zs#EnXd`P8|7*}EY>s%OB*`1s6+H_^lA@ggfK>b3tDms37P literal 0 HcmV?d00001 diff --git a/Sorting/Heap Sort/cpp/heapsort.cpp b/Sorting/Heap Sort/cpp/heapsort.cpp new file mode 100644 index 000000000..504fb0935 --- /dev/null +++ b/Sorting/Heap Sort/cpp/heapsort.cpp @@ -0,0 +1,68 @@ +// C++ program for implementation of Heap Sort +#include + +using namespace std; + +// To heapify a subtree rooted with node i which is +// an index in arr[]. n is size of heap +void heapify(int arr[], int n, int i) +{ + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 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); + } +} + +// main function to do heap sort +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