forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
69 lines (62 loc) · 1.94 KB
/
MergeSort.java
File metadata and controls
69 lines (62 loc) · 1.94 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
package com.thealgorithms.sorts;
import static com.thealgorithms.sorts.SortUtils.less;
/**
* Generic merge sort algorithm.
*
* @see SortAlgorithm
*/
class MergeSort implements SortAlgorithm {
private Comparable[] aux;
/**
* Generic merge sort algorithm implements.
*
* @param unsorted the array which should be sorted.
* @param <T> Comparable class.
* @return sorted array.
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
aux = new Comparable[unsorted.length];
doSort(unsorted, 0, unsorted.length - 1);
return unsorted;
}
/**
* @param arr the array to be sorted.
* @param left the first index of the array.
* @param right the last index of the array.
*/
private <T extends Comparable<T>> void doSort(T[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) >>> 1;
doSort(arr, left, mid);
doSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
/**
* Merges two parts of an array.
*
* @param arr the array to be merged.
* @param left the first index of the array.
* @param mid the middle index of the array.
* @param right the last index of the array merges two parts of an array in
* increasing order.
*/
@SuppressWarnings("unchecked")
private <T extends Comparable<T>> void merge(T[] arr, int left, int mid, int right) {
int i = left;
int j = mid + 1;
System.arraycopy(arr, left, aux, left, right + 1 - left);
for (int k = left; k <= right; k++) {
if (j > right) {
arr[k] = (T) aux[i++];
} else if (i > mid) {
arr[k] = (T) aux[j++];
} else if (less(aux[j], aux[i])) {
arr[k] = (T) aux[j++];
} else {
arr[k] = (T) aux[i++];
}
}
}
}