Last active
January 25, 2017 12:31
-
-
Save r3ne-pew/6d4290bfe9be4a0f183d3da66b164d1d to your computer and use it in GitHub Desktop.
C# Merge Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
namespace mergesort | |
{ | |
class MainClass | |
{ | |
public static void Main(string[] args) | |
{ | |
int count = Convert.ToInt32(Console.ReadLine()); | |
ArrayList toBeSortedA = new ArrayList(); | |
int[] toBeSortedB = new int[count]; | |
Random gen = new Random(); | |
Console.WriteLine("Unsorted"); | |
for (int i = 0; i < count; i++) | |
{ | |
int rand = gen.Next(1, 200); | |
toBeSortedA.Add(rand); | |
toBeSortedB[i] = rand; | |
Console.WriteLine(rand); | |
} | |
Console.WriteLine(""); | |
Console.WriteLine(""); | |
Console.WriteLine("Sorted:"); | |
MergeSorter ms = new MergeSorter(); | |
ms.MergeSort(toBeSortedB, 0, toBeSortedB.Length-1); | |
foreach (int a in toBeSortedB) | |
{ | |
Console.WriteLine(a); | |
} | |
} | |
} | |
class MergeSorter | |
{ | |
public MergeSorter() | |
{ | |
} | |
public void MergeSort(int[] array, int left, int right) | |
{ | |
//array -> to be sorted | |
//left -> start point | |
//right -> stop point | |
if (left >= right) return; | |
var mid = (left + right) / 2; | |
MergeSort(array, left, mid); | |
MergeSort(array, mid + 1, right); | |
Merge(array, left, mid, right); | |
} | |
private void Merge(int[] array, int start, int mid, int end) | |
{ | |
var temp = new int[end - start + 1]; | |
var leftIndex = start; | |
var rightIndex = mid + 1; | |
var arrayIndex = 0; | |
while (leftIndex <= mid && rightIndex <= end) | |
{ | |
if (array[leftIndex] <= array[rightIndex]) | |
{ | |
temp[arrayIndex] = array[leftIndex]; | |
leftIndex++; | |
} | |
else | |
{ | |
temp[arrayIndex] = array[rightIndex]; | |
rightIndex++; | |
} | |
arrayIndex++; | |
} | |
while (leftIndex <= mid) | |
{ | |
temp[arrayIndex] = array[leftIndex]; | |
leftIndex++; | |
arrayIndex++; | |
} | |
while (rightIndex <= end) | |
{ | |
temp[arrayIndex] = array[rightIndex]; | |
rightIndex++; | |
arrayIndex++; | |
} | |
for (var i = 0; i < end - start + 1; i++) | |
{ | |
array[start + i] = temp[i]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment