Created
March 14, 2021 10:36
-
-
Save phc15/2920e0d5b6794ea6b228fd266e0e1822 to your computer and use it in GitHub Desktop.
This file contains 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
public class MergeSort { | |
static void TopDownMergeSort(int[] a, int[] b, int n) { | |
CopyArray(a, 0, n, b); | |
TopDownSplitMerge(b, 0, n, a); | |
} | |
static void TopDownSplitMerge(int[] b, int left, int right, int[] a) { | |
if (right - left < 1) | |
return; | |
int mid; | |
mid = (int) Math.floor((right + left) / 2); | |
TopDownSplitMerge(a, left, mid, b); | |
TopDownSplitMerge(a, mid + 1, right, b); | |
TopDownMerge(b, left, mid, right, a); | |
} | |
static void TopDownMerge(int[] a, int left, int mid, int right, int[] b) { | |
int i = left; | |
int j = mid + 1; | |
for (int k = left; k <= right; k++) { | |
if (i <= mid && (j > right || a[i] <= a[j])) { | |
b[k] = a[i]; | |
i++; | |
} else { | |
b[k] = a[j]; | |
j++; | |
} | |
} | |
} | |
static void CopyArray(int[] a, int left, int right, int[] b) { | |
for (int k = left; k <= right; k++) { | |
b[k] = a[k]; | |
} | |
} | |
public static void main(String[] args) { | |
int[] a = { 4, 2, 11, 3, 6, 9, 1 }; | |
int[] b = new int[a.length]; | |
TopDownMergeSort(a, b, a.length - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment