C Writing the C code to find the heapsort for an array with
Solution
Please follow the code and comments for description :
CODE :
#include <iostream> // required header files
#include <cstdlib>
#include <ctime>
using namespace std;
void maxHeap(int *a, int i, int n) { // function that calculates the maximum heap of the heap sort
int j, temp; // local variables
temp = a[i];
j = 2*i;
while (j <= n) { // iterating over the loop for less than the size
if (j < n && a[j+1] > a[j]) { // conditioin to check for the value
j = j+1; // increment the value
} else if (temp > a[j]) {
break; // if is greater break the loop;
} else if (temp <= a[j]) {
a[j/2] = a[j]; // if greater replacing the values
j = 2*j; // update the value of J
}
}
a[j/2] = temp; // replacing the value
return; // return
}
void heapSort(int *a, int n) { // function that performs the heap sort algorithm
int i, temp; // local variables
for (i = n; i >= 2; i--) { // iterate over the loop
temp = a[i]; // swaping the values
a[i] = a[1];
a[1] = temp;
maxHeap(a, 1, i - 1); // call the maxHeap function to check the data
}
}
void genMaxHeap(int *a, int n) { // function that is used to drive the maxHeap sort function
int i; // local variables
for(i = n/2; i >= 1; i--) { // looping the data
maxHeap(a, i, n); // call the repsective function
}
}
int main() { // driver method
int i, x; // local variables
int a[26];
srand (time(NULL)); // rand value set to null at every iteration
for (i = 1; i <= 26; i++) { // loop over the size
a[i] = rand() % 50 + 1; // generate a random value
}
genMaxHeap(a,26); // call the function to generate the maxHeap
cout<<\"The Maximum Heap Values are as Follows : \ \";
for (i = 1; i <= 26; i++) { // loop over the size
cout<<a[i]<<endl; // print the data
}
heapSort(a, 26); // call the function to sort the data
cout<<\"The Sorted Output is : \ \";
for (i = 1; i <= 26; i++) { // loop over the data size
cout<<a[i]<<endl; // print to console
}
}
OUTPUT :
The Maximum Heap Values are as Follows :
148
147
132
137
144
116
63
121
107
76
126
105
104
47
35
27
2
87
90
8
43
5
22
95
76
71
The Sorted Output is :
2
5
8
22
27
35
43
47
71
76
76
90
95
95
95
104
107
116
121
126
126
132
137
144
147
148
Hope this is helpful.


