Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add recursive Merge Sort #279

Merged
merged 1 commit into from
Oct 3, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions recursion/MergeSort.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
namespace Merge_Sort
{
public class MergeSort
{
public static void SortBy(int[] array, int leftBorder, int rightBorder)
{
if (leftBorder >= rightBorder)
return;
int middle = (leftBorder + rightBorder) / 2;
SortBy(array, leftBorder, middle);
SortBy(array, middle+1, rightBorder);

int[] buf = new int[rightBorder-leftBorder+1];

int i = leftBorder; //index of left array
int j = middle + 1; //index of right array
int k = 0; //index of final array
while (i <= middle && j <= rightBorder)
{
if (array[i] < array[j])
buf[k++] = array[i++];
else
buf[k++] = array[j++];
}
//Add the tail of right array
while (j <= rightBorder)
buf[k++] = array[j++];
//Add the tail of left array
while (i <= middle)
buf[k++] = array[i++];

for (k = 0; k < rightBorder - leftBorder + 1; k++)
array[leftBorder + k] = buf[k];
}
}
}