-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergesort.java
More file actions
84 lines (73 loc) · 1.73 KB
/
Mergesort.java
File metadata and controls
84 lines (73 loc) · 1.73 KB
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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mergesort;
import java.util.Arrays;
/**
*
* @author Vinayak
*/
public class Mergesort {
/**
* @param args the command line arguments
*/
public static void merge_Sort(int[] m)
{
if (m.length > 1)
{
int[] left = leftside(m);
int[] right = rightside(m);
merge_Sort(left);
merge_Sort(right);
merge(m, left, right);
}
}
public static int[] leftside(int[] m)
{
int size1 = m.length / 2;
int[] left = new int[size1];
for (int i = 0; i < size1; i++)
{
left[i] = m[i];
}
return left;
}
public static int[] rightside(int[] m)
{
int size1 = m.length / 2;
int size2 = m.length - size1;
int[] right = new int[size2];
for (int i = 0; i < size2; i++)
{
right[i] = m[i + size1];
}
return right;
}
public static void merge(int[] result,
int[] left, int[] right)
{
int i1 = 0;
int i2 = 0;
for (int i = 0; i < result.length; i++)
{
if (i2 >= right.length || (i1 < left.length &&
left[i1] <= right[i2]))
{
result[i] = left[i1];
i1++;
}
else
{
result[i] = right[i2];
i2++;
}
}
}
public static void main(String[] args) {
int[]m ={95, 70, 82, 125, 48, 67, 18, 53};
merge_Sort(m);
System.out.println("Merge Sort result is: " + Arrays.toString(m));
}
}