From 5d0c19e8de267fcbccecb32ce4ce2c141a398851 Mon Sep 17 00:00:00 2001 From: Ranu Singh Date: Sat, 8 May 2021 22:34:14 +0530 Subject: [PATCH] chore(C): add Heap-sort (#285) --- algorithms/C/README.md | 1 + algorithms/C/sorting/heap-sort.c | 72 ++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 algorithms/C/sorting/heap-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 146a1501..dd299f2b 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -18,6 +18,7 @@ - [Bubble Sort](sorting/bubble-sort.c) - [Merge Sort](sorting/merge-sort.c) - [Insertion Sort](sorting/insertion-sort.c) +- [Heap Sort](sorting/heap-sort.c) ## Strings - [Count Words](strings/count-words.c) diff --git a/algorithms/C/sorting/heap-sort.c b/algorithms/C/sorting/heap-sort.c new file mode 100644 index 00000000..c94b6fcd --- /dev/null +++ b/algorithms/C/sorting/heap-sort.c @@ -0,0 +1,72 @@ +// Heap Sort in C + +#include +#include +void main() +{ + int heap[10], no, i, j, c, root, temp; + + printf("\n Enter no of elements :"); + scanf("%d", &no); + printf("\n Enter the nos : "); + for (i = 0; i < no; i++) + scanf("%d", &heap[i]); + for (i = 1; i < no; i++) + { + c = i; + do + { + root = (c - 1) / 2; + if (heap[root] < heap[c]) /* to create MAX heap array */ + { + temp = heap[root]; + heap[root] = heap[c]; + heap[c] = temp; + } + c = root; + } while (c != 0); + } + + printf("\n Heap array : "); + for (i = 0; i < no; i++) + printf("%d\t ", heap[i]); + for (j = no - 1; j >= 0; j--) + { + temp = heap[0]; + heap[0] = heap[j]; /* swap max element with rightmost leaf element */ + heap[j] = temp; + root = 0; + do + { + c = 2 * root + 1; /* left node of root element */ + if ((heap[c] < heap[c + 1]) && c < j-1) + c++; + if (heap[root]