-
Notifications
You must be signed in to change notification settings - Fork 11
/
Merge-sort.java
71 lines (48 loc) · 1.61 KB
/
Merge-sort.java
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
import java.util.*;
public class MergerSort
{
public static void main(String[] args)
{
Integer[] a = { 2, 6, 3, 5, 1 };
mergeSort(a);
System.out.println(Arrays.toString(a));
}
@SuppressWarnings("rawtypes")
public static Comparable[] mergeSort(Comparable[] list)
{
if (list.length <= 1) {
return list;
}
Comparable[] first = new Comparable[list.length / 2];
Comparable[] second = new Comparable[list.length - first.length];
System.arraycopy(list, 0, first, 0, first.length);
System.arraycopy(list, first.length, second, 0, second.length);
mergeSort(first);
mergeSort(second);
merge(first, second, list);
return list;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void merge(Comparable[] first, Comparable[] second, Comparable[] result)
{
int iFirst = 0;
int iSecond = 0;
int iMerged = 0;
while (iFirst < first.length && iSecond < second.length)
{
if (first[iFirst].compareTo(second[iSecond]) < 0)
{
result[iMerged] = first[iFirst];
iFirst++;
}
else
{
result[iMerged] = second[iSecond];
iSecond++;
}
iMerged++;
}
System.arraycopy(first, iFirst, result, iMerged, first.length - iFirst);
System.arraycopy(second, iSecond, result, iMerged, second.length - iSecond);
}
}