1 public static void main(String[] args) 2 { 3 Scanner input = new Scanner(System.in); 4 int n = input.nextInt(); 5 int[] a = new int[n]; 6 7 for(int i = 0; i < a.length; i++) 8 a[i] = input.nextInt(); 9 divide(a, 0, a.length - 1);10 11 for(int i = 0; i < a.length; i++)12 System.out.print(a[i] + " ");13 }14 15 public static void divide(int[] a, int front, int rear)16 {17 if(front == rear)18 return;19 20 int mid = front + (rear - front) / 2;21 divide(a, mid + 1, rear); //分割右半边22 divide(a, front, mid); //分割左半边23 merge(a, front, mid, rear); //进行归并24 }25 26 public static void merge(int[] a, int front, int mid, int rear)27 {28 //先依次将排好序的元素放入b数组中(在放入b数组的过程中进行排序) 再将b数组元素依次放到a数组中29 int[] b = new int[rear - front + 1];30 int k = 0, i = front, j = mid + 1;31 32 while(i <= mid && j <= rear)33 {34 if(a[i] > a[j])35 b[k++] = a[j++];36 else37 b[k++] = a[i++];38 }39 if(i > mid)40 while(j <= rear)41 b[k++] = a[j++];42 else43 while(i <= mid)44 b[k++] = a[i++];45 46 for(int p = front, q = 0; p <= rear; p++, q++)47 a[p] = b[q];48 }