Skip to content

Commit 1482014

Browse files
authored
Merge_sort in C#
Merge_sort in C#
1 parent cbe3eab commit 1482014

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

MergeSort/C_Sharp/Merge_sort.cs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System.IO;
2+
using System;
3+
4+
class Program
5+
{
6+
//By calling the sort method will sort the given array
7+
static void sort(int[] a) {
8+
int[] helper = new int[a.Length];
9+
sort(a, 0, a.Length - 1, helper);
10+
11+
}
12+
13+
static void sort(int[] a, int low, int high, int[] helper) {
14+
if (low >= high) {
15+
return;
16+
}
17+
int middle = low + (high - low) / 2;
18+
sort(a, low, middle, helper);
19+
sort(a, middle + 1, high, helper);
20+
merge(a, low, middle, high, helper);
21+
}
22+
23+
static void merge(int[] a, int low, int middle, int high, int[] helper) {
24+
for (int i = low; i <= high; i++) {
25+
helper[i] = a[i];
26+
}
27+
int x = low;
28+
int j = middle + 1;
29+
30+
for (int k = low; k <= high; k++) {
31+
if (x > middle) {
32+
a[k] = helper[j++];
33+
} else if (j > high) {
34+
a[k] = helper[x++];
35+
} else if (helper[x] <= helper[j]) {
36+
a[k] = helper[x++];
37+
} else {
38+
a[k] = helper[j++];
39+
}
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)