归并排序首先第一点就是分而治之。
第二点就是比较已分段的两组序列的元素的大小,依次放入临时数组中。
第三点就是可采用递归的方法。
import java.util.Scanner;
public class MergeSort {
private static void merge(int[] a,int[] temp,int L,int R,int rightend){
int length=rightend-L+1;
int leftend=R;
int mid=R+1;
int tmp=L;
while(L<=leftend&&mid<=rightend){
if(a[L]<a[mid]){
temp[tmp++]=a[L++];
}
else{
temp[tmp++]=a[mid++];
}
}
while(L<=leftend){
temp[tmp++]=a[L++];
}
while(mid<=rightend){
temp[tmp++]=a[mid++];
}
for(int i=0;i<length;i++,rightend--){//将临时数组的值赋给原数组,因为rightend没有改变过,执行length次
a[rightend]=temp[rightend];
}
}
private static void sort(int[] a,int[] temp,int start,int end){//将代码分段
if(start<end){
int center=(start+end)/2;
sort(a,temp,start,center);
sort(a,temp,center+1,end);
merge(a,temp,start,center,end);
}
}
public static void main(String[] args){
int n;
Scanner s=new Scanner(System.in);
n=s.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=s.nextInt();
}
int[] temp=new int[n];//创建临时数组一存放数据,注意,不是在merge()函数内部定义
sort(a,temp,0,n-1);
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
}
}
归并排序时间复杂度O(nlogn)。