Skip to content

Commit 8f97886

Browse files
authored
Create AdaptiveMergeSort.java
1 parent 1c978c5 commit 8f97886

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.thealgorithms.sorts;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* @author Anant Jain (https://github.com/anant-jain01)
7+
* @see https://en.wikipedia.org/wiki/Merge_sort
8+
*/
9+
public class AdaptiveMergeSort implements SortAlgorithm {
10+
11+
@Override
12+
public <T extends Comparable<T>> T[] sort(T[] array) {
13+
if (array == null || array.length < 2) {
14+
return array;
15+
}
16+
17+
T[] aux = array.clone();
18+
adaptiveMergeSort(array, aux, 0, array.length - 1);
19+
return array;
20+
}
21+
22+
private <T extends Comparable<T>> void adaptiveMergeSort(T[] array, T[] aux, int low, int high) {
23+
if (high <= low) return;
24+
25+
int mid = low + (high - low) / 2;
26+
27+
adaptiveMergeSort(aux, array, low, mid);
28+
adaptiveMergeSort(aux, array, mid + 1, high);
29+
30+
if (array[mid].compareTo(array[mid + 1]) <= 0) {
31+
System.arraycopy(array, low, aux, low, high - low + 1);
32+
return;
33+
}
34+
35+
merge(array, aux, low, mid, high);
36+
}
37+
38+
private <T extends Comparable<T>> void merge(T[] array, T[] aux, int low, int mid, int high) {
39+
int i = low, j = mid + 1;
40+
41+
for (int k = low; k <= high; k++) {
42+
if (i > mid) aux[k] = array[j++];
43+
else if (j > high) aux[k] = array[i++];
44+
else if (array[j].compareTo(array[i]) < 0) aux[k] = array[j++];
45+
else aux[k] = array[i++];
46+
}
47+
}
48+
49+
public static void main(String[] args) {
50+
Integer[] integers = {12, 11, 13, 5, 6, 7};
51+
AdaptiveMergeSort mergeSort = new AdaptiveMergeSort();
52+
System.out.println(Arrays.toString(mergeSort.sort(integers)));
53+
54+
String[] strings = {"zebra", "apple", "mango", "banana"};
55+
System.out.println(Arrays.toString(mergeSort.sort(strings)));
56+
}
57+
}

0 commit comments

Comments
 (0)