归并排序采用的是分治(divide-and-conquer)法思想
(1)基本思想:将待排序元素分成大小大致相同的2个子集合,分别对2个子集合进行排序,最终将排好序的子集合合并成为所要求的排好序的集合;
(2)执行过程:
(3)算法思路:
算法 MERGESORT
输入:n个元素的数组A[1...n].
输出:按非降序排列的数组A[1...n]
过程:mergesort(low,high)
1. if(low<high) then
2. mid-(low+high)/2;
3. mergesort(A,low,mid);
4. mergesort(A,mid+1,high);
5. MERGE(A,low,mid,high);
6.end if
(4)代码实现(JAVA):
public class Test{
private Integer[] nums = {3,8,9,10,7,6,5,2,4,1,11,12};
@Test
public void test() {
devideSortArray(0,nums.length-1);
}
public void devideSortArray(Integer begin,Integer end){
if (begin<end){
Integer mid = (Integer)(begin+end)/2;
System.out.print("获得"+begin+"---"+mid+"---"+end+"\n");
devideSortArray(begin,mid); //对左边序列进行归并排序
devideSortArray(mid+1,end); //对右边序列进行归并排序
caculate(begin,mid,end,nums);//合并两个有序序列
}
}
public Integer[] caculate(Integer begin,Integer mid,Integer end,Integer[] showNum){
Integer[] tempNum =new Integer[end+1]; //新建一个临时数组存放
int k = begin;
int left = begin;
int right = mid+1; //左边序列与右边序列起始索引
int cur = showNum[k];
while (left <= mid && right <=end){
if (showNum[left]>showNum[right]){
tempNum[k] = showNum[right];
right++;
k++;
}else {
tempNum[k] = showNum[left];
left++;
k++;
}
}
//左边有剩余 加入数组中
while (left<=mid){
tempNum[k] = showNum[left];
left++;
k++;
}
//右边有剩余 加入数组中
while (right<=end){
tempNum[k] = showNum[right];
k++;
right++;
}
int b = begin;
int e = end;
System.out.print("排列数--->>>>>>>\n");
for (int i = 0; i < tempNum.length; i++) {
if (tempNum[i] != null){
System.out.print("---"+tempNum[i]);
showNum[b] = tempNum[i];
b++;
}
}
System.out.print("<<<<<<<<<<\n");
return tempNum;
}
}
参考链接:
https://blog.csdn.net/javaskyhr/article/details/88527431
http://www.360doc.com/content/19/1020/21/26884319_868046433.shtml
&spm=1001.2101.3001.5002&articleId=106283628&d=1&t=3&u=e3b99e2370844cd99bf7192aae8f6db1)
1万+

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



