1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.util.Arrays;
public class MergeSort { public static void mergeSort(int[] arr) { if (arr == null || arr.length <= 1) return; int[] temp = new int[arr.length]; mergeSort(arr, 0, arr.length - 1, temp); }
private static void mergeSort(int[] arr, int left, int right, int[] temp) { if (left >= right) return; int mid = left + (right - left) / 2; mergeSort(arr, left, mid, temp); mergeSort(arr, mid + 1, right, temp); merge(arr, left, mid, right, temp); }
private static void merge(int[] arr, int left, int mid, int right, int[] temp) { int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } }
while (i <= mid) temp[k++] = arr[i++]; while (j <= right) temp[k++] = arr[j++];
System.arraycopy(temp, 0, arr, left, k); }
public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; mergeSort(arr); System.out.print("Sorted: "); for (int num : arr) { System.out.print(num + " "); } } }
|