forked from Harry-003/Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.txt
85 lines (75 loc) · 2.07 KB
/
mergesort.txt
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
class Merge {
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
/* temporary Arrays */
int LeftArray[] = new int[n1];
int RightArray[] = new int[n2];
/* copy data to temp arrays */
for (i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
i = 0; /* initial index of first sub-array */
j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */
while (i < n1 && j < n2)
{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
/* Function to print the array */
void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
public static void main(String args[])
{
int a[] = { 11, 30, 24, 7, 31, 16, 39, 41 };
int n = a.length;
Merge m1 = new Merge();
System.out.println("\nBefore sorting array elements are - ");
m1.printArray(a, n);
m1.mergeSort(a, 0, n - 1);
System.out.println("\nAfter sorting array elements are - ");
m1.printArray(a, n);
System.out.println("");
}
}