import java.util.Arrays; public class Main { public static void main(String[] args) { int[] a = { 6, -2, 7, 8, 3, 4, 12, 1, 0, -3, -8, 3, 4, 7 }; System.out.println("排序之前:" + Arrays.toString(a)); sort(a, 0, a.length - 1); System.out.println("排序之後:" + Arrays.toString(a)); } public static int[] sort(int[] a, int low, int high) { int mid = (low + high) / 2; if (low < high) { sort(a, low, mid); sort(a, mid + 1, high); merge(a, low, mid, high); } return a; } public static void merge(int[] a, int low, int mid, int high) { int[] temp = new int[high - low + 1]; int i = low; int j = mid + 1; int k = 0; // 將兩數組中較小的放入temp while (i <= mid && j <= high) { if (a[i] < a[j]) { temp[k] = a[i]; k++; i++; } else { temp[k] = a[j]; k++; j++; } } // 將剩余的放入temp while (i <= mid) { temp[k] = a[i]; k++; i++; } while (j <= high) { temp[k] = a[j]; k++; j++; } // 用temp覆蓋a for (int k2 = 0; k2 < temp.length; k2++) { a[k2 + low] = temp[k2]; } } }