Skip to content

Commit e22bf5f

Browse files
authored
This is a .c Sorting program.
In this program we use to sorting Heap methord.
1 parent 02e86b7 commit e22bf5f

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

heap_sort.c

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
#define MAX_HEAP_SIZE 100
5+
6+
// Structure for the max heap
7+
typedef struct {
8+
int items[MAX_HEAP_SIZE];
9+
int size;
10+
} MaxHeap;
11+
12+
// Function to swap two elements in the heap
13+
void swap(int* a, int* b) {
14+
int temp = *a;
15+
*a = *b;
16+
*b = temp;
17+
}
18+
19+
// Function to maintain the max heap property after inserting an element
20+
void heapifyUp(MaxHeap* heap, int index) {
21+
while (index > 0 && heap->items[(index - 1) / 2] < heap->items[index]) {
22+
swap(&heap->items[(index - 1) / 2], &heap->items[index]);
23+
index = (index - 1) / 2;
24+
}
25+
}
26+
27+
// Function to maintain the max heap property after removing the root
28+
void heapifyDown(MaxHeap* heap, int index) {
29+
int largest = index;
30+
int leftChild = 2 * index + 1;
31+
int rightChild = 2 * index + 2;
32+
33+
if (leftChild < heap->size && heap->items[leftChild] > heap->items[largest])
34+
largest = leftChild;
35+
if (rightChild < heap->size && heap->items[rightChild] > heap->items[largest])
36+
largest = rightChild;
37+
38+
if (largest != index) {
39+
swap(&heap->items[index], &heap->items[largest]);
40+
heapifyDown(heap, largest);
41+
}
42+
}
43+
44+
// Function to insert an element into the heap
45+
void insert(MaxHeap* heap, int value) {
46+
if (heap->size >= MAX_HEAP_SIZE) {
47+
printf("Heap is full. Cannot insert.\n");
48+
return;
49+
}
50+
heap->items[heap->size] = value;
51+
heap->size++;
52+
heapifyUp(heap, heap->size - 1);
53+
}
54+
55+
// Function to delete the root (maximum value) from the heap
56+
int deleteMax(MaxHeap* heap) {
57+
if (heap->size == 0) {
58+
printf("Heap is empty. Cannot delete.\n");
59+
return -1;
60+
}
61+
int deletedItem = heap->items[0];
62+
heap->items[0] = heap->items[heap->size - 1];
63+
heap->size--;
64+
heapifyDown(heap, 0);
65+
return deletedItem;
66+
}
67+
68+
// Function to perform heap sort
69+
void heapSort(int arr[], int n) {
70+
MaxHeap heap;
71+
heap.size = 0;
72+
73+
// Inserting elements into the max heap
74+
for (int i = 0; i < n; i++) {
75+
insert(&heap, arr[i]);
76+
}
77+
78+
// Deleting elements from the max heap and storing them in sorted order
79+
for (int i = n - 1; i >= 0; i--) {
80+
arr[i] = deleteMax(&heap);
81+
}
82+
}
83+
84+
int main() {
85+
int arr[] = {4, 10, 3, 5, 1};
86+
int n = sizeof(arr) / sizeof(arr[0]);
87+
88+
// Performing heap sort
89+
heapSort(arr, n);
90+
91+
// Displaying sorted array
92+
printf("Sorted array: ");
93+
for (int i = 0; i < n; i++) {
94+
printf("%d ", arr[i]);
95+
}
96+
printf("\n");
97+
98+
return 0;
99+
}

0 commit comments

Comments
 (0)