import java.util.Arrays; public class MergeSort { public static void main(String[] args) { MergeSort sort = new MergeSort(); int[] a = {2,4,3,1,0,9,5,6,3,7}; int[] r = sort.sort(a); for(int i = 0 ; i < r.length ; i++){ System.out.println(r[i]); } } private int[] sort(int[] a){ if(a.length == 1) return a; else{ int center = a.length / 2; int[] left = Arrays.copyOfRange(a, 0, center); int[] right = Arrays.copyOfRange(a, center, a.length); int[] leftResult = sort(left); int[] rightResult = sort(right); return merge(leftResult,rightResult); } } private int[] merge(int[] a , int[] b){ int[] c = new int[a.length + b.length]; int count = 0 , i = 0 , j = 0; for(; i < a.length && j < b.length ;){ c[count++] = a[i] < b[j] ? a[i++] : b[j++]; } int size = a.length - i > 0 ? a.length - i : b.length - j; boolean sign = a.length - i > 0 ? true : false; if(size > 0){ if(sign){ for(int k = count ; k < c.length ;){ c[k++] = a[i++]; } }else{ for(int k = count ; k < c.length ;){ c[k++] = b[j++]; } } } return c; } }