Created
October 11, 2019 04:27
-
-
Save easleyschool/75506c6bb1293df27b3a68593bb45603 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Below program is written in C language */ | |
# include <stdio.h> | |
void heapify(int arr[], int n, int i) | |
{ | |
int largest = i; | |
int l = 2*i + 1; | |
int r = 2*i + 2; | |
// if left child is larger than root | |
if (l < n && arr[l] > arr[largest]) | |
largest = l; | |
// if right child is larger than the largest so far | |
if (r < n && arr[r] > arr[largest]) | |
largest = r; | |
// if largest is not root | |
if (largest != i) | |
{ | |
swap(arr[i], arr[largest]); | |
// recursively heapify the affected sub-tree | |
heapify(arr, n, largest); | |
} | |
} | |
void heapSort(int arr[], int n) | |
{ | |
// build heap (rearrange array) | |
for (int i = n / 2 - 1; i >= 0; i--) | |
heapify(arr, n, i); | |
// one by one extract an element from heap | |
for (int i=n-1; i>=0; i--) | |
{ | |
// move current root to end | |
swap(arr[0], arr[i]); | |
// call max heapify on the reduced heap | |
heapify(arr, i, 0); | |
} | |
} | |
// function to print the array of given size | |
void printArray(int a[], int size) | |
{ | |
int i; | |
for (i=0; i < size; i++) | |
{ | |
printf("%d ", a[i]); | |
} | |
printf("\n"); | |
} | |
int main() | |
{ | |
int arr[] = {121, 10, 130, 57, 36, 17}; | |
int n = sizeof(arr)/sizeof(arr[0]); | |
heapSort(arr, n); | |
printf( "Sorted array is \n"); | |
printArray(arr, n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment