1.归并排序
1.1 算法思想
将待排序序列中的前后相邻的的两个序列合并成一个有序序列
1.2 算法图解

1.3 代码与结果
public class MergeSort {
public static void main(String[] args) {
int a[]={49,38,65,97,76,13,27,49};
Msort(a,0,a.length-1);
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
public static void Merge(int[] a,int low,int mid,int high)
{
int[] temp =new int[high-low+1];
int p1 =low;
int p2=mid+1;
int i=0;
while(p1<=mid&&p2<=high)
{
temp[i++]=a[p1]<a[p2]?a[p1++]:a[p2++];
}
while(p1<=mid)
{
temp[i++]=a[p1++];
}
while(p2<=high)
{
temp[i++]=a[p2++];
}
for(int j=0;j<temp.length;j++)
{
a[low+j]=temp[j];
}
}
public static void Msort(int[] a,int low,int high)
{
if(low==high)
{
return;
}
int mid = (low+high)/2;
Msort(a,low,mid);
Msort(a,mid+1,high);
Merge(a,low,mid,high);
}
}
13 27 38 49 49 65 76 97
1.4 总结
1.4.1 平均时间复杂度O(nlogn),空间复杂度O(n);
1.4.2 是稳定排序
2261

被折叠的 条评论
为什么被折叠?



