Skip to content

Instantly share code, notes, and snippets.

@topnotch48
Created November 2, 2018 07:48
Show Gist options
  • Save topnotch48/0ac3aa5fea088303518d7b2ef97f9a8f to your computer and use it in GitHub Desktop.
Save topnotch48/0ac3aa5fea088303518d7b2ef97f9a8f to your computer and use it in GitHub Desktop.
class MergeSort
{
public static void MergeSort(int[] input, int low, int high)
{
if (low < high)
{
int middle = (low + high) / 2;
MergeSort(input, low, middle);
MergeSort(input, middle + 1, high);
Merge(input, low, middle, high);
}
}
public static void MergeSort(int[] input)
{
MergeSort(input, 0, input.Length - 1);
}
private static void Merge(int[] input, int low, int middle, int high)
{
int left = low;
int right = middle + 1;
int[] tmp = new int[(high - low) + 1];
int tmpIndex = 0;
while ((left <= middle) && (right <= high))
{
if (input[left] < input[right])
{
tmp[tmpIndex] = input[left];
left = left + 1;
}
else
{
tmp[tmpIndex] = input[right];
right = right + 1;
}
tmpIndex = tmpIndex + 1;
}
while (left <= middle)
{
tmp[tmpIndex] = input[left];
left = left + 1;
tmpIndex = tmpIndex + 1;
}
while (right <= high)
{
tmp[tmpIndex] = input[right];
right = right + 1;
tmpIndex = tmpIndex + 1;
}
for (int i = 0; i < tmp.Length; i++)
{
input[low + i] = tmp[i];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment