归并排序java

时间:2022-08-04 11:37:10
 import java.util.Arrays;

 public class MergeSort {

     public static void main(String[] args) {
MergeSort ms=new MergeSort();
int[] arr={5,44,32,4,566,67,23};
ms.merge(arr, 0, arr.length-1);
System.out.println(Arrays.toString(arr));
} void merge(int[] arr,int start,int end )
{
if(start==end)
return ;
int mid=(start+end)/2;
merge(arr,start,mid);//左边排序递归
merge(arr,mid+1,end);//you边排序递归
combine(arr,start,mid,end);
} void combine(int[] arr,int start,int mid,int end) {
int length=end-start+1;
int tempArr[]=new int[length];
int tempIndex=0;
int left=start;
int right=mid+1;
while(left<=mid&&right<=end)
{
if(arr[left]<arr[right])
tempArr[tempIndex++]=arr[left++];
else
tempArr[tempIndex++]=arr[right++];
} while(left<=mid)
tempArr[tempIndex++]=arr[left++]; while(right<=end)
tempArr[tempIndex++]=arr[right++]; for(int i=0;i<tempArr.length;i++)
{
arr[start+i]=tempArr[i];
}
}
}