提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
`
归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。
提示:以下是本篇文章正文内容,下面案例可供参考
一、思想
将数组分成两段,再将这两段再分成两段,一直二分,直到只有两个元素,将这两个元素排序放在新的数组里,作为一组,同样另外分成的一组也是,再将这两组合并成一个组,同一层上的组不断排序重组,最后再进行一个遍历比较排序(这种用指针悬停,移动,比较,排序的方法有点像快速排序,但是和快速排序是完全不一样的,这个在最后一步的时候是保证两部分是有序的,所以只要循环比较,一个一个放在新数组中就能得到有序数组)
二、代码及分析
1.代码实现
代码如下(示例):
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] array = {5,2,6,4,7,1,8,3};
int[] temp = new int[array.length];
mSort(array,0, array.length - 1,temp);
System.out.println(Arrays.toString(array));
}
public static void mSort(int[] array,int left,int right,int[] temp){
if (left < right){
int mid = (left + right)/2;
//向左进行分解
mSort(array,left,mid,temp);
//向右分解
mSort(array,mid + 1,right,temp);
//归并
sort(array,left,right,mid,temp);
//这里加两行输出是为了在输出时看清过程
System.out.println(Arrays.toString(temp));
System.out.println(Arrays.toString(array));
}
}
public static void sort(int array[],int left,int right,int mid,int temp[]){
int i = left;//指向左边序列的开始位置
int j = mid + 1;//指向右边序列的开始位置
int t = 0;//用来记录临时数组的下标
while (i <= mid && j <= right){
if (array[i] <= array[j]){
temp[t] = array[i];
t++;
i++;
}else {
temp[t] = array[j];
t++;
j++;
}
}
//将左边有序序列剩余的元素平移到temp
while (i <= mid){
temp[t] = array[i];
t++;
i++;
}
while (j <= right){
temp[t] = array[j];
t++;
j++;
}
//把临时数组中的元素拷贝到array中去
t = 0;
while (left <= right){
array[left]= temp[t];
left++;
t++;
}
}
}
2.输出结果
代码如下(示例):
[2, 5, 0, 0, 0, 0, 0, 0] temp中先排25
[2, 5, 6, 4, 7, 1, 8, 3] 放在array
[4, 6, 0, 0, 0, 0, 0, 0] temp中排46
[2, 5, 4, 6, 7, 1, 8, 3] 放在array
[2, 4, 5, 6, 0, 0, 0, 0] temp中排2546
[2, 4, 5, 6, 7, 1, 8, 3] 放在array
[1, 7, 5, 6, 0, 0, 0, 0] temp中排17(因为temp并不空,本来有2456,这里可以当成一个空的数组来看待理解)
[2, 4, 5, 6, 1, 7, 8, 3] 放在array
[3, 8, 5, 6, 0, 0, 0, 0] temp中排38(因为temp并不空,本来有1756,这里可以当成一个空的数组来看待理解)
[2, 4, 5, 6, 1, 7, 3, 8] 放在array
[1, 3, 7, 8, 0, 0, 0, 0] temp中排1738
[2, 4, 5, 6, 1, 3, 7, 8] 放在array
[1, 2, 3, 4, 5, 6, 7, 8] 在temp中排24561378(这里就是最后一步,也是最能体现上面的sort方法思想的)
[1, 2, 3, 4, 5, 6, 7, 8] 放在array
[1, 2, 3, 4, 5, 6, 7, 8] main中的输出
630

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



