public class MergeSort { public static int[] mergeSort(int[] array){ int[] temp = array.clone(); divide(array,temp,0,array.length-1); return array; } private static int[] divide(int[] array,int[] temp,int start,int end){ if (start == end) return array; if ((end-start)==1) { if (array[start]>array[end]){ ArrayUtil.exchangeNums(array,start,end); ArrayUtil.exchangeNums(temp,start,end); return array; } } int mid = start+(end-start)/2; divide(array,temp,start,mid); divide(array,temp,mid+1,end); merge(array,temp,start,mid,end); return array; } private static int[] merge(int[] array, int[] temp,int start, int mid, int end) { int preindex = start; int forindex = mid+1; int index = start; while (preindex<=mid & forindex<=end){ if (array[preindex] < array[forindex]){ temp[index++] = array[preindex++]; }else if (array[forindex] < array[preindex]){ temp[index++] = array[forindex++]; } else if (array[preindex] == array[forindex]){ temp[index++] = array[preindex++]; temp[index++] = array[forindex++]; } } if (preindex>mid && forindex<=end){ while(forindex<=end){ temp[index++] = array[forindex++]; } } if (forindex>end && preindex<=mid){ while (preindex<=mid){ temp[index++] = array[preindex++]; } } for (int i=start;i<=end;i++){ array[i] = temp[i]; } return array; } }
|