#include<stdio.h>
void merge_sort(int *a,int *b,int x,int y)
{ if(y-x>1) { int m=x+(y-x)/2;//中间点的坐标 int p=x,q=m,i=x; merge_sort(a,b,x,m); merge_sort(a,b,m,y); while(p<=m||q<y) { if(q>=y||(p<m&&a[p]<=a[q])) b[i++]=a[p++];//从左半数组复 制到临时空间 else b[i++]=a[q++];// 从右半 数组复制到临时空间 } for(i=x;i<y;i++) a[i]=b[i]; }
}
int main()
{ int b[100],a[100],n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); int mid=n/2; merge_sort(a,b,0,n); for(int i=0;i<n;i++) printf("%d ",a[i]); return 0;
}
2018/03/27更新添加java代码:
package com.tjrac_java_2;import java.util.Scanner;public class MargeSort {public static void main(String[] args) {int[] a = new int[5];Scanner sc = new Scanner(System.in);for (int i = 0; i < a.length; i++) {a[i] = sc.nextInt();}int[] temp = new int[5];marge_sort(a, 0, 5, temp);for (int i = 0; i < a.length; i++) {System.out.println(a[i]);}}private static void marge_sort(int[] a, int left, int right, int[] temp) {// 1.递归出口if (right - left > 1) {int mid = left + (right - left) / 2;int pLeft = left, qRight = mid, i = left;marge_sort(a, left, mid, temp);marge_sort(a, mid, right, temp);// 从左半边数组复制到临时空间while (pLeft < mid || qRight < right) {//qRight>=right是当右半边的数组都小于左半边的数组时,先把右半边数组放在临时空间,然后再放左半边数组,因此不用再进行比较左右两边数组了if (qRight >= right || (pLeft < mid && a[pLeft] <= a[qRight])) {temp[i++] = a[pLeft++];} else {// 从右半 数组复制到临时空间temp[i++] = a[qRight++];}}for (int j = left; j < right; j++) {a[j] = temp[j];}}}
}