-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
63 lines (47 loc) · 1.68 KB
/
MergeSort.java
File metadata and controls
63 lines (47 loc) · 1.68 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
/**
* Created by Phil on 8/15/2015.
*/
public class MergeSort {
public MergeSort() {}
public int[] sort(int[] collection) {
System.out.println("Pre-sorted: ");
for(int i = 0; i < collection.length; i++) {
System.out.print(collection[i] + " ");
}
System.out.println();
mergeSort(collection, 0, collection.length - 1);
System.out.println("Post-sorted: ");
for(int i = 0; i < collection.length; i++) {
System.out.print(collection[i] + " ");
}
return collection;
}
private void mergeSort(int[] collection, int leftIndex, int rightIndex) {
if(leftIndex >= rightIndex) return;
int midPoint = leftIndex + (rightIndex - leftIndex)/2;
mergeSort(collection, leftIndex, midPoint);
mergeSort(collection, midPoint + 1, rightIndex);
merge(collection, leftIndex, midPoint, rightIndex);
}
private void merge(int[] collection, int leftIndex, int midPoint, int rightIndex) {
int[] copy = collection.clone();
int index = leftIndex;
int i = leftIndex;
int j = midPoint+1;
while(i <= midPoint && j <= rightIndex) {
if(copy[i] <= copy[j])
collection[index++] = copy[i++];
else
collection[index++] = copy[j++];
}
while( i <= midPoint)
collection[index++] = copy[i++];
while(j <= rightIndex)
collection[index++] = copy[j++];
}
public static void main(String[] args) {
MergeSort ms = new MergeSort();
int[] unsorted = {6,8,2,3,7,1,9,10,43,2,5,25,43,21,75};
ms.sort(unsorted);
}
}