public class MergeSort {
public static void main(String[] args) {
int[] nums={9,8,7,6,5,4,3,2,1};
mergeSort(nums,0,nums.length-1);
for(int i=0;i<nums.length;i++){
System.out.println(nums[i]);
}
}
static void mergeSort(int[] nums, int left, int right){
// 递归出口
if(left==right){
return;
}
if(left+1==right){
if(nums[left]>nums[right]){
swap(nums,left,right);
}
return;
}
// 先划分
int mid=(left+right)/2;
mergeSort(nums,left,mid);
mergeSort(nums,mid+1,right);
// 再合并
merge(nums,left,mid,right);
}
static void swap(int[] nums, int index1, int index2){
int temp=nums[index1];
nums[index1]=nums[index2];
nums[index2]=temp;
}
static void merge(int[] nums,int left,int mid, int right){
int[] result=new int[nums.length];
int i=left,j=mid+1,k=left;
while(i<=mid && j<=right){
if(nums[i]<=nums[j]){
result[k++]=nums[i++];
}
else{
result[k++]=nums[j++];
}
}
while(i<=mid){
result[k++]=nums[i++];
}
while(j<=right){
result[k++]=nums[j++];
}
for(int l=left;l<=right;l++){
nums[l]=result[l];
}
}
}
04-28
530
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-22
1362
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-30
746
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-18
565
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)