1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public class Mergesort { public static void main(String[] args) { int[] array = new int[]{5,2,4,1,6,8,10,7,9,3}; sort(array); for(int i=0;i<array.length;i++){ System.out.println(array[i]); } }
public static void sort(int[] array){ int[] temp = new int[array.length]; sort(array,0,array.length-1,temp); }
public static void sort(int[] array,int start,int end,int[] temp){ if(start < end){ int mid = (end - start) / 2 + start; sort(array,start,mid,temp); sort(array,mid + 1,end,temp); merge(array,start,end,temp); } } public static void merge(int[] array,int start,int end,int[] temp){ int mid = (end - start) / 2 + start; int i = start; int j = mid + 1; int t = 0; while(i <= mid && j <= end){ if(array[i] <= array[j]){ temp[t++] = array[i++]; } else { temp[t++] = array[j++]; } } while(i <= mid){ temp[t++] = array[i++]; } while(j <= end){ temp[t++] = array[j++]; }
t = 0; while(start <= end){ array[start++] = temp[t++]; } } }
|