import java.util.*;
public final class Test {
public static void printf(int []a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
System.out.print("\n");
}
public static void sort(int []a,int left,int right,int []temp)
{
if(left<right)
{
int mid=(left+right)/2;
sort(a,left,mid,temp);//左边区间
sort(a,mid+1,right,temp);//右边区间
merge(a,left,mid,right,temp);//左右合并
}
}
public static void merge(int []a,int left,int mid,int right,int []temp)
{
int i=left;
int j=mid+1;
int t=0;
while (i<=mid&&j<=right)
{
if(a[i]<=a[j])
{
temp[t++]=a[i++];
}
else
{
temp[t++]=a[j++];
}
}
while (i<=mid)
{
temp[t++]=a[i++];
}
while (j<=right)
{
temp[t++]=a[j++];
}
t=0;
while (left<=right)
{
a[left++]=temp[t++];
}
}
public static void main(String[]args)
{
int[]test={1,8,4,5,7,9,3,10};
int[]temp=new int[test.length];
sort(test,0,test.length-1,temp);
printf(test);
}
}
```转自https://www.cnblogs.com/chengxiao/p/6194356.html
归并排序
最新推荐文章于 2024-03-26 17:18:09 发布