fork download
  1. #include <iostream>
  2. #include <algorithm> // For sort
  3. using namespace std;
  4.  
  5. // Generic function to calculate the median
  6. template <class T>
  7. T CalculateMedian(T arr[], int size) {
  8. // Sort the array
  9. sort(arr, arr + size);
  10.  
  11. // If the size is odd, return the middle element
  12. if (size % 2 != 0) {
  13. return arr[size / 2];
  14. }
  15. // If the size is even, return the average of the two middle elements
  16. else {
  17. return (arr[(size / 2) - 1] + arr[size / 2]) / 2.0;
  18. }
  19. }
  20.  
  21. int main() {
  22. // Test with integers
  23. int intArr[] = {10, 2, 5, 8, 1};
  24. int intSize = sizeof(intArr) / sizeof(intArr[0]);
  25. cout << "Median (int): " << CalculateMedian(intArr, intSize) << endl;
  26.  
  27. // Test with floating-point values
  28. double doubleArr[] = {2.5, 1.0, 3.5, 4.0, 6.0};
  29. int doubleSize = sizeof(doubleArr) / sizeof(doubleArr[0]);
  30. cout << "Median (double): " << CalculateMedian(doubleArr, doubleSize) << endl;
  31.  
  32. // Test with characters
  33. char charArr[] = {'z', 'a', 'g', 'm', 'b'};
  34. int charSize = sizeof(charArr) / sizeof(charArr[0]);
  35. cout << "Median (char): " << CalculateMedian(charArr, charSize) << endl;
  36.  
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Median (int): 5
Median (double): 3.5
Median (char): g