算法思路
分治法,分而治之
1.分解,将待排序数组分为两个子序列,每个子序列含有n/2个元素。
2. 治理,将每个子序列调用MergeSort,进行递归操作。
3. 合并,合并两个排好序的子序列,生成排序结果。
代码实现
import java.util.Arrays;
public class MergeSort {
public static int[] sort(int[] a,int low,int high){
int mid=(low+high)/2;
if(low<high){
sort(a,low,mid);
sort(a,mid+1,low); // 左右归并
merge(a,low,mid,high);
}
return a;
}
public static void merge(int[] a,int low,int mid,int high){
int[] temp=new int[high-low+1];
int i=low;
int j=mid+1;
int k=0;
//将较小的数放在新数组中
while(i<=mid&&j<=high){
if(a[i]<a[j]){
temp[k++]=a[i++];
}else{
temp[k++]=a[j++];
}
}
//将左边剩余的数移入数组
while(i<=mid){
temp[k++]=a[i++];
}
//将右边剩余的数移入数组
while(j<=high){
temp[k++]=a[j++];
}
//将新数组中的数覆盖nums数组
for(int x=0;x<temp.length;x++){
a[low+x]=temp[x];
}
}
public static void main(String[] args)
{
int[] a={1,33,15,9,11,45,66};
sort(a,1,5);
System.out.println(Arrays.toString(a));
}
}
复杂度分析
O(nlogn)
运行结果