# 归并排序 Merge sort

public class MergeSort {
public static final int CUTOFF = 11;

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a;
int n = 300;
// 生产随机数组
a = new int[n];
Random rand = new Random();
for ( int i = 0; i < a. length; i++) {
a[i] = rand.nextInt(n);
}
//a = new int [] {33,10,80};
println(a);

long s = System. nanoTime();
int[] b = mergeSort(a);
long dur = System. nanoTime() - s;
println(b);
System. out.println(dur);

}

public static int[] mergeSort( int[] a) {
int[] tmp = new int[a. length];
split(a, tmp, 0, a.length-1);
return tmp;
}

public static void split(int[] a, int[] tmp, int left, int right) {
//System.out.println(left+","+right);
if (left < right) {
int center = (left + right) / 2;
//System.out.println(center);
split(a, tmp, left, center);
split(a, tmp, center + 1, right);
merge(a,tmp,left,center+1,right);
}
//System.out.println("返回");
}
public static void merge(int[] a,int[] tmp,int lPos,int rPos,int rEnd){
//System.out.println("merge:"+lPos+","+rPos+","+rEnd);
int lEnd = rPos -1;
int tPos = lPos;
int leftTmp = lPos;
while(lPos <= lEnd && rPos <= rEnd){
if(a[lPos] <= a[rPos]){
tmp[tPos++] = a[lPos++];
} else{
tmp[tPos++] = a[rPos++];
}
}

while(lPos <= lEnd){
tmp[tPos++] = a[lPos++];
}

while(rPos <= rEnd){
tmp[tPos++] = a[rPos++];
}
// copy the tmpArr back cause we need to change the arr array items.
for ( ; rEnd >= leftTmp; rEnd-- )
a[rEnd] = tmp[rEnd];

}

public static void println(int[] a) {
System. out.print( "[");
for ( int i = 0; i < a. length; i++) {
System. out.print(a[i]);
if (i != a. length - 1)
System. out.print( ",");
}
System. out.println( "]");
}

}

#### In-place Merge Sort (原地归并排序)

2011-10-11 15:42:09

#### 面试之路（16）-归并排序详解（MergeSort）递归和非递归实现

2016-05-01 16:58:42

#### C语言-数据结构-归并排序(merge sort)-递归 迭代-源代码及分析

2017-01-25 21:30:06

#### 排序算法详解【归并排序-Merge_Sort】

2014-04-04 13:42:43

#### C++实现归并排序Mergesort（使用递归的方法）

2017-01-10 11:57:42

#### 链表和归并排序(Merge Sort)

2014-12-12 11:01:27

#### 无聊写排序之 ---- 归并排序(MergeSort) 非递归实现

2014-10-29 11:09:40

#### 经典排序算法以及负载平衡下的平行归并排序Parallel Merge Sort with Load Balancing

2016-06-09 17:45:43

#### 排序——归并排序（Merge Sort）及应用

2016-02-26 13:01:58

#### 使用C#详解常用排序算法（三）：归并排序（Merge Sort）

2015-08-09 23:35:17