From 2a41d916b05681932021d4130f19af21097f385b Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 17:38:42 +0530 Subject: [PATCH] Added template and test cases --- sorting/heap_sort.cpp | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 6cdb17f4a..5eaded62a 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -23,6 +23,8 @@ * */ #include +#include +#include /** * @@ -33,7 +35,8 @@ * @param sz size of array * */ -void printArray(int *arr, int sz) { +template +void printArray(T *arr, int sz) { for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; std::cout << "\n"; } @@ -50,7 +53,8 @@ void printArray(int *arr, int sz) { * Array to be compared with it's childern * */ -void heapify(int *arr, int n, int i) { +template +void heapify(T *arr, int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; @@ -75,7 +79,8 @@ void heapify(int *arr, int n, int i) { * @param n size of array * */ -void heapSort(int *arr, int n) { +template +void heapSort(T *arr, int n) { for (int i = n - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { @@ -84,13 +89,27 @@ void heapSort(int *arr, int n) { } } -/** Main function */ -int main() { +void test() { + std::cout << "Test 1\n"; int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array printArray(arr, sz); // displaying the array before sorting heapSort(arr, sz); // calling heapsort to sort the array printArray(arr, sz); // display array after sorting - return 0; + assert(std::is_sorted(arr, arr+sz)); + std::cout << "Test 1 Passed\n========================\n"; + std::cout << "Test 2\n"; + double arr2[] = {4.5, -3.6, 7.6, 0, 12.9}; + sz = sizeof(arr2) / sizeof(arr2[0]); + printArray(arr2, sz); + heapSort(arr2, sz); + printArray(arr2, sz); + assert(std::is_sorted(arr2, arr2+sz)); + std::cout << "Test 2 passed\n"; +} +/** Main function */ +int main() { + test(); + return 0; } /** @} */