Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Practical Azure SQL Database For Modern Developers Building Applications In The Microsoft Cloud

Authors: Davide Mauri, Silvano Coriani, Anna Hoffma, Sanjay Mishra, Jovan Popovic

1st Edition

1484263693, 978-1484263693

More Books

Students also viewed these Databases questions