Skip to content

Commit 9b485b7

Browse files
authored
Create AdaptiveMergeSort.java
1 parent 822dbe8 commit 9b485b7

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.thealgorithms.sorts;
2+
3+
public class AdaptiveMergeSort implements SortAlgorithm {
4+
5+
@SuppressWarnings("unchecked")
6+
public <T extends Comparable<T>> T[] sort(T[] array) {
7+
if (array.length <= 1) {
8+
return array;
9+
}
10+
T[] aux = array.clone();
11+
sort(array, aux, 0, array.length - 1);
12+
return array;
13+
}
14+
15+
private <T extends Comparable<T>> void sort(T[] array, T[] aux, int low, int high) {
16+
if (low >= high) {
17+
return;
18+
}
19+
int mid = low + (high - low) / 2;
20+
sort(array, aux, low, mid);
21+
sort(array, aux, mid + 1, high);
22+
merge(array, aux, low, mid, high);
23+
}
24+
25+
private <T extends Comparable<T>> void merge(T[] array, T[] aux, int low, int mid, int high) {
26+
for (int k = low; k <= high; k++) {
27+
aux[k] = array[k];
28+
}
29+
30+
int i = low, j = mid + 1;
31+
for (int k = low; k <= high; k++) {
32+
if (i > mid) array[k] = aux[j++];
33+
else if (j > high) array[k] = aux[i++];
34+
else if (aux[j].compareTo(aux[i]) < 0) array[k] = aux[j++];
35+
else array[k] = aux[i++];
36+
}
37+
}
38+
39+
public static void main(String[] args) {
40+
AdaptiveMergeSort adaptiveMergeSort = new AdaptiveMergeSort();
41+
42+
// Integer Input
43+
Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
44+
SortUtils.print(adaptiveMergeSort.sort(integers));
45+
46+
// String Input
47+
String[] strings = {"c", "a", "e", "b", "d"};
48+
SortUtils.print(adaptiveMergeSort.sort(strings));
49+
}
50+
}

0 commit comments

Comments
 (0)