public class MergeSort { public static void main(String[] args) { int[] arr = new int[]{2,5,6,4,8,5,4,1,22,3,45}; merge(arr,0,arr.length-1); System.out.println(Arrays.toString(arr)); } public static void merge(int arr[],int left,int right) { if(left ==right) { return; } int mid = (left +right) / 2; merge(arr,left,mid); merge(arr,mid+1,right); he(arr,left,mid,right); } public static void he(int[] arr,int left,int mid,int right) { int s1=left; int s2 = mid+1; int index=0; int temp[] = new int[right-left+1]; while(s1<=mid&&s2<=right) { if(arr[s1]<=arr[s2]) { temp[index]=arr[s1]; s1++; index++; } else { temp[index] = arr[s2]; s2++; index++; } } while(s1<=mid) { temp[index] = arr[s1]; index++; s1++; } while(s2<=right) { temp[index] = arr[s2]; index++; s2++; } for(int i = 0;i<temp.length;i++) { arr[i+left] = temp[i]; } } }
采用了分治思想