heap sort

 HEAP SORT 





#include <stdio.h>

void swap(int *a, int *b) {

    int temp = *a;

    *a = *b;

    *b = temp;

}

void heapify(int a[], int n, int i) {

    int largest = i; 

    int left = 2 * i + 1;

    int right = 2 * i + 2; 

    if (left < n && a[left] > a[largest])

        largest = left;

    if (right < n && a[right] > a[largest])

        largest = right;

    if (largest != i) {

        swap(&a[i], &a[largest]);

        heapify(a, n, largest);

    }

}

void heapSort(int a[], int n) {

    int i;

    for (i = n / 2 - 1; i >= 0; i--)

        heapify(a, n, i);

    for (i = n - 1; i >= 0; i--) {

        swap(&a[0], &a[i]);

        heapify(a, i, 0);

    }

}

int main() {

    int n, i;

    printf("Enter number of elements: ");

    scanf("%d", &n);

    int a[n];

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++)

{

        scanf("%d", &a[i]);

}

    heapSort(a, n);

    printf("\nSorted array: ");

    for (i = 0; i < n; i++)

{

        printf("%d ", a[i]);

}

    printf("\n");

    return 0;

}







OUTPUT:

Enter number of elements: 5

Enter 5 elements:

8 43 24 13 1

Sorted array: 1 8 13 24 43 


Comments

Popular posts from this blog

SINGLE LINKED LIST by smd

CLL by smd

QUEUE USING ARRAYS by smd