rendered paste body#include <stdio.h>#include <stdlib.h>#include <sys/time.h>#define _RAND(a, b) 1 + (int)((float)(b) * (rand() / (RAND_MAX + (float)(a))))#define TIMERSUB(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0)struct SortProc { char *name; void *proc;};void siftdown(int array[], int start, int end){ int parent = start, child; int tmp; while ((child = (parent * 2 + 1)) <= end) { //taking the bigger of two siblings if (child < end && array[child] < array[child + 1]) child++; //swapping the parent and the child if latter is bigger if (array[parent] < array[child]) { tmp = array[child]; array[child] = array[parent]; array[parent] = tmp; parent = child; //iterating down the tree } else return; }}void heapify(int array[], int count){ int start; start = count / 2 - 1; //taking the last parent //heapifying array by iterating downsifts while (start) siftdown(array, start--, count - 1);}void heapsort(int array[], int count){ //shape array to meet binary heap's constraints heapify(array, count); int end; int tmp; end = count - 1; while (end) { //swap the tail element with the root tmp = array[end]; array[end] = array[0]; array[0] = tmp; //squeeze the array by one element end--; //restore heap properties siftdown(array, 0, end); } return; //array is now sorted}void bubblesort(int array[], int count){ int swapped; int i, tmp; do { swapped = 0; for (i = 0; i < count - 1; i++) { if (array[i] > array[i + 1]) { tmp = array[i]; array[i] = array[i + 1]; array[i + 1] = tmp; swapped = 1; } } } while (swapped); }void filldata(int array[], int count){ int i; for (i = 0; i < count; i++) { array[i] = _RAND(1, 100); }}void output(char *str, int array[], int count){ int i; printf("%s ", str); for (i = 0; i < count; i++) { printf("%d ", array[i]); } putchar('\n');}float testsort(int iters, int size, void(sortproc)(int[], int)){ struct timeval t1, t2, tres; int i; int *data = malloc(sizeof(int) * size); gettimeofday(&t1, NULL); while (iters) { filldata(data, size); //output("Unsorted:", data, size); sortproc(data, size); //output("Sorted:", data, size); iters--; } gettimeofday(&t2, NULL); TIMERSUB(&t2, &t1, &tres); return tres.tv_sec + ((float)tres.tv_usec / 1000000);}int main(int argc, char **argv){ int i, size, iters; float t; struct SortProc sorts[] = { {"heapsort", heapsort}, {"bubble sort", bubblesort} }; srand(time(NULL)); if (argc > 2) { iters = atoi(argv[2]); } else iters = 10000; if (argc > 1) { size = atoi(argv[1]); } else size = 500; printf("Array size: %d; Iterations: %d\n", size, iters); for (i = 0; i < sizeof(sorts)/sizeof(struct SortProc); i++) { printf("%s: ", sorts[i].name); t = testsort(iters, size, sorts[i].proc); printf("%2.2f\n", t); } return 0;}