forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_sort.cs
99 lines (82 loc) · 2.12 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
This is implementation of Merge Sort in C#
Merge Sort is a Divide and Conquer algorithm.
It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves.
The conquer_merge() function is used for merging two halves.
*/
using System;
public class Merge_Sort
{
public static int[] temp;
// Conquer
public static void conquer_merge(int[] array, int left, int right, int mid)
{
int k = left, i, j;
for(i = left, j = mid + 1; i <= mid && j <= right; k++)
{
if(array[i] <= array[j])
{
temp[k] = array[i];
i++;
}
else
{
temp[k] = array[j];
j++;
}
}
while(i <= mid)
{
temp[k] = array[i];
i++;
k++;
}
while(j <= right)
{
temp[k] = array[j];
j++;
k++;
}
for(i = left; i <= right; i++)
array[i] = temp[i];
}
// Divide array into halves
public static void divide(int[] array, int left, int right)
{
if(left < right)
{
int mid = left + (right - left) / 2;
divide(array, left, mid);
divide(array, mid + 1, right);
conquer_merge(array, left, right, mid);
}
}
public static void MergeSort(int[] array, int size)
{
temp = new int[size];
divide(array, 0, size - 1);
temp = null;
}
// function ro print array
public static void Print_Array(int[] array, int size)
{
for(int i = 0; i < size; i++)
Console.Write(array[i] + " ");
Console.Write("");
}
public static void Main()
{
int size;
size= Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for(int i=0; i<size; i++)
array[i] = Convert.ToInt32(Console.ReadLine());
MergeSort(array, size);
Print_Array(array, size);
}
}
// input
// 7
// 6 2 1 3 4 8 4
// Output
// 1 2 3 4 4 6 8