Skip to content

Commit 3242fad

Browse files
authored
Create AdaptiveMergeSort.java
1 parent 1c978c5 commit 3242fad

File tree

1 file changed

+54
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)