Advertisement
Guest User

Untitled

a guest
Jul 31st, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. /// <summary>
  2. /// Finds the median in an array
  3. /// Uses an efficient sorting on a copy of the array
  4. /// </summary>
  5. /// <param name="array">The array</param>
  6. /// <returns>The median of the array</returns>
  7. public static int SortBasedMedian(int[] array)
  8. {
  9. int[] copy = (int[])array.Clone();
  10. Array.Sort(copy);
  11. return copy[copy.Length / 2];
  12. }
  13.  
  14. /// <summary>
  15. /// Finds the median in an array
  16. /// Uses a counting method
  17. /// </summary>
  18. /// <param name="array">The array</param>
  19. /// <returns>The median of the array</returns>
  20. public static int CountingBasedMedian(int[] array)
  21. {
  22. for (int i = 0; i < array.Length; i++)
  23. {
  24. int lessThen = 0, greaterThen = 0;
  25. for (int j = 0; j < array.Length; j++)
  26. {
  27. if (array[j] < array[i])
  28. lessThen++;
  29. else if (array[j] > array[i])
  30. greaterThen++;
  31. }
  32. if (lessThen == greaterThen)
  33. return array[i];
  34. }
  35. throw new Exception("Impossible!");
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement