Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Sortable_Collection.Sorters
- {
- using Contracts;
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- public class AsyncMergeSorter<T> : ISorter<T> where T : IComparable<T>
- {
- public void Sort(IList<T> collection)
- {
- if (collection.Count <= 1)
- {
- return;
- }
- T[] workArray = new T[collection.Count];
- SplitMerge(collection, workArray, 0, collection.Count);
- }
- private void SplitMerge(IList<T> collection, T[] tempArray, int start, int end)
- {
- if (end - start < 2)
- {
- return;
- }
- int midd = (start + end) / 2;
- if (end - start < 15000)
- {
- SplitMerge(collection, tempArray, start, midd);
- SplitMerge(collection, tempArray, midd, end);
- }
- else
- {
- Task t1 = Task.Factory.StartNew(() => SplitMerge(collection, tempArray, start, midd));
- Task t2 = Task.Factory.StartNew(() => SplitMerge(collection, tempArray, midd, end));
- Task.WaitAll(t1, t2);
- }
- //SplitMerge(collection, tempArray, start, midd);
- //SplitMerge(collection, tempArray, midd, end);
- Merge(collection, tempArray, start, midd, end);
- CoppyArray(collection, tempArray, start, end);
- }
- private void Merge(IList<T> collection, T[] tempArray, int start, int midd, int end)
- {
- int first = start;
- int second = midd;
- for (int i = start; i < end; i++)
- {
- if (first >= midd)
- {
- tempArray[i] = collection[second++];
- }
- else if (second >= end)
- {
- tempArray[i] = collection[first++];
- }
- else
- {
- if (collection[first].CompareTo(collection[second]) <= 0)
- {
- tempArray[i] = collection[first++];
- }
- else
- {
- tempArray[i] = collection[second++];
- }
- }
- }
- }
- private void CoppyArray(IList<T> collection, T[] tempArray, int start, int end)
- {
- for (int i = start; i < end; i++)
- {
- collection[i] = tempArray[i];
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement