#include <iostream>
#include <algorithm> // For sort
using namespace std;
// Generic function to calculate the median
template <class T>
T CalculateMedian(T arr[], int size) {
// Sort the array
sort(arr, arr + size);
// If the size is odd, return the middle element
if (size % 2 != 0) {
return arr[size / 2];
}
// If the size is even, return the average of the two middle elements
else {
return (arr[(size / 2) - 1] + arr[size / 2]) / 2.0;
}
}
int main() {
// Test with integers
int intArr[] = {10, 2, 5, 8, 1};
int intSize = sizeof(intArr) / sizeof(intArr[0]);
cout << "Median (int): " << CalculateMedian(intArr, intSize) << endl;
// Test with floating-point values
double doubleArr[] = {2.5, 1.0, 3.5, 4.0, 6.0};
int doubleSize = sizeof(doubleArr) / sizeof(doubleArr[0]);
cout << "Median (double): " << CalculateMedian(doubleArr, doubleSize) << endl;
// Test with characters
char charArr[] = {'z', 'a', 'g', 'm', 'b'};
int charSize = sizeof(charArr) / sizeof(charArr[0]);
cout << "Median (char): " << CalculateMedian(charArr, charSize) << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8YWxnb3JpdGhtPiAvLyBGb3Igc29ydAp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKLy8gR2VuZXJpYyBmdW5jdGlvbiB0byBjYWxjdWxhdGUgdGhlIG1lZGlhbgp0ZW1wbGF0ZSA8Y2xhc3MgVD4KVCBDYWxjdWxhdGVNZWRpYW4oVCBhcnJbXSwgaW50IHNpemUpIHsKICAgIC8vIFNvcnQgdGhlIGFycmF5CiAgICBzb3J0KGFyciwgYXJyICsgc2l6ZSk7CgogICAgLy8gSWYgdGhlIHNpemUgaXMgb2RkLCByZXR1cm4gdGhlIG1pZGRsZSBlbGVtZW50CiAgICBpZiAoc2l6ZSAlIDIgIT0gMCkgewogICAgICAgIHJldHVybiBhcnJbc2l6ZSAvIDJdOwogICAgfSAKICAgIC8vIElmIHRoZSBzaXplIGlzIGV2ZW4sIHJldHVybiB0aGUgYXZlcmFnZSBvZiB0aGUgdHdvIG1pZGRsZSBlbGVtZW50cw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