Tuesday, October 28
Merge Sort MultiThreading in C#; multithreaded
int[] MergeSort(int[] input, int start, int end) { if (end - start < 2) { int[] result = new int[1]; result[0] = input[start]; return (result); } Task<int[]> Tleft = Task<int[]>.Factory.StartNew(() => { return MergeSort(input, start, (start + end) / 2); }); Task<int[]> Tright = Task<int[]>.Factory.StartNew(() => { return MergeSort(input, (start + end) / 2, end); }); //Task<int[]>.WaitAll(new Task<int[]>[]{Tleft,Tright}); int[] left = Tleft.Result; int[] right = Tright.Result; int[] Result = Task<int[]>.Factory.StartNew(() => { return Merge(left, right); }).Result; Console.WriteLine(getText(Result)); return Result; } int[] Merge(int[] left, int[] right) { int leftSize = left.Length, rightSize = right.Length; int[] result = new int[leftSize + rightSize]; int leftIndex = 0, rightIndex = 0, resultIndex = 0; while (rightIndex < rightSize && leftIndex < leftSize) { result[resultIndex++] = left[leftIndex] < right[rightIndex] ? left[leftIndex++] : right[rightIndex++]; } while (rightIndex < rightSize) result[resultIndex++] = right[rightIndex++]; while (leftIndex < leftSize) result[resultIndex++] = left[leftIndex++]; return result; }
0 comments :
Post a Comment