Added template and test cases

This commit is contained in:
Ayaan Khan 2020-06-21 17:38:42 +05:30
parent 86bd671c66
commit 2a41d916b0

View File

@ -23,6 +23,8 @@
* *
*/ */
#include <iostream> #include <iostream>
#include <algorithm>
#include <cassert>
/** /**
* *
@ -33,7 +35,8 @@
* @param sz size of array * @param sz size of array
* *
*/ */
void printArray(int *arr, int sz) { template <typename T>
void printArray(T *arr, int sz) {
for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; for (int i = 0; i < sz; i++) std::cout << arr[i] << " ";
std::cout << "\n"; std::cout << "\n";
} }
@ -50,7 +53,8 @@ void printArray(int *arr, int sz) {
* Array to be compared with it's childern * Array to be compared with it's childern
* *
*/ */
void heapify(int *arr, int n, int i) { template <typename T>
void heapify(T *arr, int n, int i) {
int largest = i; int largest = i;
int l = 2 * i + 1; int l = 2 * i + 1;
int r = 2 * i + 2; int r = 2 * i + 2;
@ -75,7 +79,8 @@ void heapify(int *arr, int n, int i) {
* @param n size of array * @param n size of array
* *
*/ */
void heapSort(int *arr, int n) { template <typename T>
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--) heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) { for (int i = n - 1; i >= 0; i--) {
@ -84,13 +89,27 @@ void heapSort(int *arr, int n) {
} }
} }
/** Main function */ void test() {
int main() { std::cout << "Test 1\n";
int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0};
int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array
printArray(arr, sz); // displaying the array before sorting printArray(arr, sz); // displaying the array before sorting
heapSort(arr, sz); // calling heapsort to sort the array heapSort(arr, sz); // calling heapsort to sort the array
printArray(arr, sz); // display array after sorting printArray(arr, sz); // display array after sorting
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; return 0;
} }
/** @} */ /** @} */