This repository has been archived by the owner on May 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 793
/
Copy pathmerge-sort.cs
67 lines (56 loc) · 1.87 KB
/
merge-sort.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections.Generic;
using System.Text;
namespace Algorithms.Sorts
{
public class MergeSort
{
public static List<int> Sort(List<int> numbers)
{
Divide(numbers, 0, numbers.Count - 1);
return numbers;
}
public static void Merge(List<int> numbers, int left, int mid, int right)
{
List<int> leftPartition = new List<int>();
List<int> rightPartition = new List<int>();
for(int i = left; i <= mid; i++)
{
leftPartition.Add(numbers[i]);
}
for(int i = mid + 1; i <= right; i++)
{
rightPartition.Add(numbers[i]);
}
int l = 0, r = 0;
int size1 = leftPartition.Count, size2 = rightPartition.Count;
for(int i = left; i <= right; i++)
{
if((l < size1 && r >= size2) || (l < size1 && r < size2 && leftPartition[l] < rightPartition[r]))
{
numbers[i] = leftPartition[l++];
}
else
{
numbers[i] = rightPartition[r++];
}
}
}
public static void Divide(List<int> numbers, int left, int right)
{
if(left < right)
{
int mid = (left + right) / 2;
Divide(numbers, left, mid);
Divide(numbers, mid + 1, right);
Merge(numbers, left, mid, right);
}
}
public static void Main()
{
List<int> numbers = new List<int> { 9, 1, -1, 10, 12, 2, 0, 0, -2, -9 , 107};
List<int> answer = Sort(numbers);
Console.WriteLine(string.Join(", ", answer));
}
}
}