C program that implements Heap sorting methods to sort a given list of integers in ascending order
C program that implements Heap sorting methods to sort a given list of integers in ascending order
Heap sorting methods
#include <stdio.h>
// Function to swap two elements
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
/* heapify the subtree with root i */
void heapify(int* arr, int n, int i)
{
// store largest as the root element
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
// now check whether the right and left right is larger than the root or not
if (left < n && arr[left] > arr[largest])
{
largest = left;
}
if (right < n && arr[right] > arr[largest])
{
largest = right;
}
// if the root is smaller than the children then swap it with the largest children's value
if (largest != i)
{
swap(&arr[i], &arr[largest]);
// again heapify that side of the heap where the root has gone
heapify(arr, n, largest);
}
}
/* sorts the given array of n size */
void heapsort(int* arr, int n)
{
// build the binary max heap
for (int i = n / 2 - 1; i >= 0; i--)
{
heapify(arr, n, i);
}
// sort the max heap
for (int i = n - 1; i >= 0; i--)
{
// swap the root node and the last leaf node
swap(&arr[i], &arr[0]);
// again heapify the max heap from the root
heapify(arr, i, 0);
}
}
int main() {
int n,arr[20],i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
heapsort(arr, n);
printf("Sorted array: ");
for(i=0;i
OUTPUT
Enter number of elements: 9
Enter 9 integers:
7 4 1 8 5 2 9 6 3
Sorted array: 1 2 3 4 5 6 7 8 9
π» Run This C Program
C program that implements Heap sorting methods to sort a given list of integers in ascending order
The selected C program is loaded automatically.
Edit the code, provide input through STDIN and
click Run.
The compiler is embedded using OneCompiler.
Your program runs in the embedded C environment;
Study Glance does not execute C code directly on
your web server.