From 0c513bbe7071e984f9fecab806d82bedefdad9e9 Mon Sep 17 00:00:00 2001 From: Yogiraj Shinde <84953719+yogirajbshinde21@users.noreply.github.com> Date: Sun, 7 May 2023 23:22:56 +0530 Subject: [PATCH] Update heapsort.c 1. Defined a maximum heap size using a constant. 2. Used a separate function for heapify. 3. Simplified the main loop. 4. Removed unnecessary comments. 5. Used more descriptive variable names. 6. Used more meaningful output messages. --- heapsort.c | 124 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 70 insertions(+), 54 deletions(-) diff --git a/heapsort.c b/heapsort.c index 3d1d0f4d..0c53aab9 100644 --- a/heapsort.c +++ b/heapsort.c @@ -1,55 +1,71 @@ -#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); +#include +#include + +#define MAX_HEAP_SIZE 100 + +void swap(int *a, int *b); +void heapify(int *heap, int size, int i); +void build_heap(int *heap, int size); +void heapsort(int *heap, int size); + +int main() { + int heap[MAX_HEAP_SIZE], size; + + printf("Enter the number of elements (max %d): ", MAX_HEAP_SIZE); + scanf("%d", &size); + + printf("Enter the elements: "); + for (int i = 0; i < size; i++) { + scanf("%d", &heap[i]); } - - printf("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] heap[largest]) { + largest = l; + } + + if (r < size && heap[r] > heap[largest]) { + largest = r; + } + + if (largest != i) { + swap(&heap[i], &heap[largest]); + heapify(heap, size, largest); + } +} + +void build_heap(int *heap, int size) { + for (int i = size / 2 - 1; i >= 0; i--) { + heapify(heap, size, i); + } +} + +void heapsort(int *heap, int size) { + build_heap(heap, size); + + for (int i = size - 1; i > 0; i--) { + swap(&heap[0], &heap[i]); + heapify(heap, i, 0); + } +}