Question: Write a main function to test your heap sort implementation: - Initialize an array of integers, e . g . , int arr [ ]

Write a main function to test your heap sort implementation:
- Initialize an array of integers, e.g., int arr[]={12,11,13,5,6,7};.
- Print the original array.
- Sort the array using the heap sort function.
- Print the sorted array.
Sample Output:
Original array: 121113567
Sorted array: 567111213
In C Language Please!!
Heap Sort Function:
#include
// Function to swap two elements
void swap(int* a, int* b){
int temp =*a;
*a =*b;
*b = temp;
}
// Function to heapify a subtree rooted with node i
void heapify(int arr[], int n, int i){
int largest = i; // Initialize largest as root
int left =2* i +1; // left child index
int right =2* i +2; // right child index
// If left child is larger than root
if (left < n && arr[left]> arr[largest])
largest = left;
// If right child is larger than largest so far
if (right < n && arr[right]> arr[largest])
largest = right;
// If largest is not root
if (largest != i){
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// Function to perform heap sort
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 heapify on the reduced heap
heapify(arr, i,0);
}
}
// Function to print an array
void printArray(int arr[], int n){
for (int i =0; i < n; i++)
printf("%d ", arr[i]);
printf("
");
}
int main(){
int arr[]={12,11,13,5,6,7};
int n = sizeof(arr)/ sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
heapSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!