Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static T[] MergeSort<T>(this T[] array, IComparer<T> comparer = null)
- {
- if (comparer == null)
- comparer = Comparer<T>.Default;
- _MergeSort(array, 0, array.Length - 1, comparer);
- return array;
- }
- private static void _MergeSort<T>(T[] array, int startIndex, int endIndex, IComparer<T> comparer)
- {
- if (startIndex >= endIndex)
- return;
- int middle = (startIndex + endIndex) / 2;
- _MergeSort(array, startIndex, middle, comparer);
- _MergeSort(array, middle + 1, endIndex, comparer);
- Merge(array, startIndex, endIndex, middle, comparer);
- }
- private static void Merge<T>(T[] array, int startIndex, int endIndex, int middle, IComparer<T> comparer)
- {
- int leftSize = middle - startIndex + 1;
- int rightSize = endIndex - middle;
- T[] leftArray = new T[leftSize],
- rightArray = new T[rightSize];
- for (int i = 0; i < leftSize; i++)
- leftArray[i] = array[startIndex + i];
- for (int j = 0; j < rightSize; j++)
- rightArray[j] = array[middle + 1 + j];
- int leftIndex = 0, rightIndex = 0, currentIndex = startIndex;
- while (leftIndex < leftSize && rightIndex < rightSize)
- {
- if (comparer.Compare(leftArray[leftIndex], rightArray[rightIndex]) <= 0) // left smaller or equal
- {
- array[currentIndex] = leftArray[leftIndex];
- leftIndex++;
- }
- else
- {
- array[currentIndex] = rightArray[rightIndex];
- rightIndex++;
- }
- currentIndex++;
- }
- while(leftIndex < leftSize)
- {
- array[currentIndex] = leftArray[leftIndex];
- leftIndex++;
- currentIndex++;
- }
- while (rightIndex < rightSize)
- {
- array[currentIndex] = rightArray[rightIndex];
- rightIndex++;
- currentIndex++;
- }
- }
Add Comment
Please, Sign In to add comment