归并排序递归实现

 1 /*
 2  * 归并排序递归实现
 3  * 简介:将两个(或两个以上)有序表合并成一个新的有序表 即把待排序序列分为若干个子序列,每个子序列是有序的。
 4  * 然后再把有序子序列合并为整体有序序列 
 5  * 时间复杂度为O(nlogn) 
 6  * 
 7  * */
 8 
 9 import java.util.Arrays;
10 
11 public class MegerSort {
12     public int[] sort(int[] k,int low,int high)
13     {
14         int center=(low+high)/2;  //获取数组中间位置
15         if(low<high)
16         {
17             sort(k,low,center);   //对左边进行递归调用
18             sort(k,center+1,high);//对右边进行递归调用
19             merge(k,low,center,high); //先分成两半,然后再归并起来
20         }
21         return k;
22     }
23     public void merge(int[] k,int low, int center,int high)
24     {
25         int[] temp=new int[high-low+1]; //声明一个可以存放一定大小的数组,
26         int i=low; //左边起始位置
27         int j=center+1; //右边起始位置
28         int m=0; 
29         //对左右数组进行比较排序
30         while(i<=center && j<=high)
31         {
32             if(k[i]<k[j])
33             {
34                 temp[m++]=k[i++];
35             }
36             else 
37             {
38                 temp[m++]=k[j++];
39             }
40         }
41         while(i<=center)  //当左边数组还没遍历完时,直接添加在后面
42         {
43             temp[m++]=k[i++];
44             
45         }
46         while(j<=high)//当右边数组还没遍历完时,直接添加在后面
47         {
48             temp[m++]=k[j++];
49             
50         }
51          // 把新数组中的数覆盖k数组  
52         for(int n=0;n<temp.length;n++) 
53         {
54             k[n+low]=temp[n];
55         }
56     }
57 
58     public static void main(String[] args) {
59         // TODO Auto-generated method stub
60         MegerSort sort = new MegerSort();
61         int[] A ={5,7,2,9,8,6,1,3,4,0};
62         System.out.println("排序前的顺序:");
63         System.out.println(Arrays.toString(A));
64         sort.sort(A, 0, A.length-1);
65         System.out.println();
66         System.out.println("使用归并排序后的顺序为");
67         System.out.println(Arrays.toString(A));
68         
69     }
70 
71 }
原文地址:https://www.cnblogs.com/luoweiKnowledge/p/3960364.html