Created
June 23, 2021 18:42
-
-
Save vslala/f783aa92acb43dc8663b6b041afc9f45 to your computer and use it in GitHub Desktop.
Iterative Merge Sort A.K.A Bottom Up Merge Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class BottomUpMergeSort implements Sort { | |
@Override | |
public int[] sort(int[] input) { | |
var arr = Arrays.copyOf(input, input.length); | |
var aux = new int[input.length]; | |
for (var width = 1; width < arr.length; width = 2 * width) { | |
int i; | |
for (i = 0; i < arr.length; i = i + 2 * width) { | |
int left = i; // start index of array 1 | |
int middle = i + width; // start index of second array or the end index of first array | |
int end = i + 2 * width; // end of the second array | |
merge(arr, left, middle, end, aux); | |
} | |
for (i = 0; i < arr.length; i++) { | |
arr[i] = aux[i]; | |
} | |
} | |
return arr; | |
} | |
private void merge(int[] arr, int left, int middle, int end, int[] aux) { | |
int i = left; | |
int j = middle; | |
int k = left; | |
while (i < middle || j < end) { | |
if (i < middle && j < end) { | |
if (arr[i] < arr[j]) aux[k++] = arr[i++]; | |
else aux[k++] = arr[j++]; | |
} | |
else if (i == middle) aux[k++] = arr[j++]; | |
else if (j == end) aux[k++] = arr[i++]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment