归并排序是采用分治的思想,使用先分在归并起来的逻辑,归并排序其最吸引人的性质是它能够
保证将任意长度为N的数组排序所需时间和NLogN成正比。其主要思想是先不断递归进行二分,然后
通过合并的时候进行子数组的排序不断的合并完成排序。
测试数据 4 2 1 5
第一步 先二分数据即
[4,2] [1,5]
[4] [2] [1] [5]
第二步 这是所有数据单独被划分出来了,然后开始进行合并操作,每次合并会把合并的元素进行
排序
[2,4] [1,5]
[1,2,4,5]
(由于在合并时,合并的两个数组是已经有序了的,故排序是采用中间索引划分出两个数组进行轮
换比对,比如[2,4,1,5] 中间索引值为1。首先取出2与1进行比对,然后将1放入一个临时数组
的第一位,如此往复比对,最后将比对完成的数据放入原数组中)
参考代码
public static int[] sort(int[] reslut)
{
int [] temp=new int[reslut.length];
sort(reslut,0,reslut.length-1,temp);
return reslut;
}
public static void sort(int[] reslut,int left,int rghit,int[] temp)
{
if(left<rghit)
{
//递归步骤,先二分,然后排序左边,在排序右边,然后进行归并处理
int middle=(left+rghit)/2;
sort(reslut,left,middle,temp);
sort(reslut,middle+1,rghit,temp);
merge(reslut,left,middle,rghit,temp);
}
}
public static void merge(int[] reslut,int left,int mid,int rghit,int[] temp)
{
int i=left;
int j=mid+1;
int t=0;
while (i<=mid && j<=rghit)
{
if(reslut[i]<=reslut[j])
{
temp[t++]=reslut[i++];
}else
{
temp[t++]=reslut[j++];
}
}
while (i<=mid)
{
temp[t++]=reslut[i++];
}
while (j<=rghit)
{
temp[t++]=reslut[j++];
}
t=0;
while (left<=rghit)
{
reslut[left++]=temp[t++];
}
}