Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using BenchmarkDotNet.Attributes;
- namespace Task4C
- {
- [MemoryDiagnoser]
- public class MergedSort
- {
- private int[] _numbers;
- private void Merge(int[] array, int lowIndex, int middleIndex, int highIndex)
- {
- var left = lowIndex;
- var right = middleIndex + 1;
- var tempArray = new int[highIndex - lowIndex + 1];
- var index = 0;
- while ((left <= middleIndex) && (right <= highIndex))
- {
- if (array[left] < array[right])
- {
- tempArray[index] = array[left];
- left++;
- }
- else
- {
- tempArray[index] = array[right];
- right++;
- }
- index++;
- }
- for (var i = left; i <= middleIndex; i++)
- {
- tempArray[index] = array[i];
- index++;
- }
- for (var i = right; i <= highIndex; i++)
- {
- tempArray[index] = array[i];
- index++;
- }
- for (var i = 0; i < tempArray.Length; i++)
- {
- array[lowIndex + i] = tempArray[i];
- }
- }
- private int[] MergeSort(int[] array, int lowIndex, int highIndex)
- {
- if (lowIndex < highIndex)
- {
- var middleIndex = (lowIndex + highIndex) / 2;
- MergeSort(array, lowIndex, middleIndex);
- MergeSort(array, middleIndex + 1, highIndex);
- Merge(array, lowIndex, middleIndex, highIndex);
- }
- return array;
- }
- [Benchmark]
- public void MergeSort()
- {
- MergeSort(_numbers, 0, _numbers.Length - 1);
- }
- [IterationSetup]
- public void MakeArray()
- {
- var number = new Random();
- var arr = new int[2000];
- for (var i = 0; i < arr.Length; i++) {
- arr[i] = number.Next();
- }
- _numbers = arr;
- }
- }
- }
Add Comment
Please, Sign In to add comment