Guest User

Untitled

a guest
Mar 16th, 2022
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace Algorithms.Sorters.Comparison {
  4.     public class MergeSorter<T> : IComparisonSorter<T> {
  5.         public void Sort(T[] array, IComparer<T> comparer) {
  6.             if (array.Length <= 1) return;
  7.             var (left, right) = Split(array);
  8.             Sort(left, comparer);
  9.             Sort(right, comparer);
  10.             Merge(array, left, right, comparer);
  11.         }
  12.         private static void Merge(T[] array, T[] left, T[] right, IComparer<T> comparer) {
  13.             int mainIndex = 0, leftIndex = 0, rightIndex = 0;
  14.             while (leftIndex < left.Length && rightIndex < right.Length) {
  15.                 var compResult = comparer.Compare(left[leftIndex], right[rightIndex]);
  16.                 array[mainIndex++] = compResult <= 0 ? left[leftIndex++] : right[rightIndex++];
  17.             }
  18.             while (leftIndex < left.Length) {
  19.                 array[mainIndex++] = left[leftIndex++];
  20.             }
  21.             while (rightIndex < right.Length) {
  22.                 array[mainIndex++] = right[rightIndex++];
  23.             }
  24.         }
  25.         private static (T[] left, T[] right) Split(T[] array) {
  26.             var mid = array.Length / 2;
  27.             return (array.Take(mid).ToArray(), array.Skip(mid).ToArray());
  28.         }
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment