fork(2) download
  1. using System;
  2.  
  3. public class Test
  4. {
  5. public static decimal GetMedian(int[] array)
  6. {
  7. int[] tempArray = array;
  8. int count = tempArray.Length;
  9.  
  10. Array.Sort(tempArray);
  11.  
  12. decimal medianValue = 0;
  13.  
  14. if (count % 2 == 0)
  15. {
  16. // count is even, need to get the middle two elements, add them together, then divide by 2
  17. int middleElement1 = tempArray[(count / 2) - 1];
  18. int middleElement2 = tempArray[(count / 2)];
  19. medianValue = (middleElement1 + middleElement2) / 2;
  20. }
  21. else
  22. {
  23. // count is odd, simply get the middle element.
  24. medianValue = tempArray[(count / 2)];
  25. }
  26.  
  27. return medianValue;
  28. }
  29.  
  30. public static void Main()
  31. {
  32. Console.Write("Median Value: ");
  33. int[] items = new int[] {12, 5, 2, 16};
  34. var median = GetMedian(items);
  35. Console.WriteLine(median);
  36. }
  37. }
Success #stdin #stdout 0s 131776KB
stdin
Standard input is empty
stdout
Median Value: 8