Skip to content

Create AdaptiveMergeSort.java #5726

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/main/java/com/thealgorithms/sorts/AdaptiveMergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.thealgorithms.sorts;

import java.util.Arrays;

/**
* @author Anant Jain (https://github.com/anant-jain01)
* @see https://en.wikipedia.org/wiki/Merge_sort
*/
public class AdaptiveMergeSort implements SortAlgorithm {

@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array == null || array.length < 2) {
return array;
}

T[] aux = array.clone();
adaptiveMergeSort(array, aux, 0, array.length - 1);
return array;
}

private <T extends Comparable<T>> void adaptiveMergeSort(T[] array, T[] aux, int low, int high) {
if (high <= low) return;

int mid = low + (high - low) / 2;

adaptiveMergeSort(aux, array, low, mid);
adaptiveMergeSort(aux, array, mid + 1, high);

if (array[mid].compareTo(array[mid + 1]) <= 0) {
System.arraycopy(array, low, aux, low, high - low + 1);
return;
}

merge(array, aux, low, mid, high);
}

private <T extends Comparable<T>> void merge(T[] array, T[] aux, int low, int mid, int high) {
int i = low, j = mid + 1;

for (int k = low; k <= high; k++) {
if (i > mid) aux[k] = array[j++];
else if (j > high) aux[k] = array[i++];
else if (array[j].compareTo(array[i]) < 0) aux[k] = array[j++];
else aux[k] = array[i++];
}
}

public static void main(String[] args) {
Integer[] integers = {12, 11, 13, 5, 6, 7};
AdaptiveMergeSort mergeSort = new AdaptiveMergeSort();
System.out.println(Arrays.toString(mergeSort.sort(integers)));

String[] strings = {"zebra", "apple", "mango", "banana"};
System.out.println(Arrays.toString(mergeSort.sort(strings)));
}
}
Loading