Guest User

Untitled

a guest
Feb 24th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. public static T[] MergeSort<T>(this T[] array, IComparer<T> comparer = null)
  2. {
  3. if (comparer == null)
  4. comparer = Comparer<T>.Default;
  5.  
  6. _MergeSort(array, 0, array.Length - 1, comparer);
  7.  
  8. return array;
  9.  
  10. }
  11.  
  12. private static void _MergeSort<T>(T[] array, int startIndex, int endIndex, IComparer<T> comparer)
  13. {
  14. if (startIndex >= endIndex)
  15. return;
  16.  
  17. int middle = (startIndex + endIndex) / 2;
  18.  
  19. _MergeSort(array, startIndex, middle, comparer);
  20. _MergeSort(array, middle + 1, endIndex, comparer);
  21. Merge(array, startIndex, endIndex, middle, comparer);
  22. }
  23.  
  24. private static void Merge<T>(T[] array, int startIndex, int endIndex, int middle, IComparer<T> comparer)
  25. {
  26. int leftSize = middle - startIndex + 1;
  27. int rightSize = endIndex - middle;
  28.  
  29. T[] leftArray = new T[leftSize],
  30. rightArray = new T[rightSize];
  31.  
  32. for (int i = 0; i < leftSize; i++)
  33. leftArray[i] = array[startIndex + i];
  34. for (int j = 0; j < rightSize; j++)
  35. rightArray[j] = array[middle + 1 + j];
  36.  
  37.  
  38. int leftIndex = 0, rightIndex = 0, currentIndex = startIndex;
  39. while (leftIndex < leftSize && rightIndex < rightSize)
  40. {
  41. if (comparer.Compare(leftArray[leftIndex], rightArray[rightIndex]) <= 0) // left smaller or equal
  42. {
  43. array[currentIndex] = leftArray[leftIndex];
  44. leftIndex++;
  45. }
  46. else
  47. {
  48. array[currentIndex] = rightArray[rightIndex];
  49. rightIndex++;
  50. }
  51. currentIndex++;
  52. }
  53.  
  54. while(leftIndex < leftSize)
  55. {
  56. array[currentIndex] = leftArray[leftIndex];
  57. leftIndex++;
  58. currentIndex++;
  59. }
  60.  
  61. while (rightIndex < rightSize)
  62. {
  63. array[currentIndex] = rightArray[rightIndex];
  64. rightIndex++;
  65. currentIndex++;
  66. }
  67. }
Add Comment
Please, Sign In to add comment