归并排序思想:将一个序列分成两半然后对两半分别排序,再将他们归并为一个有序序列。
归并排序图解:
归并排序的代码:(迭代版本代码由于写的急,没来的急优化,所以可读性不是很好)
//递归版本归并排序
public class Recursion_MergeSort {
public static <T extends Comparable<? super T>>
void merge_Sort(T[] a,int first,int last){
T[] tempArray=(T[])new Comparable<?>[a.length];
mergeSort(a,tempArray,first,last);
}
public static <T extends Comparable<? super T>>
void mergeSort(T[] a,T[] tempArray,int first,int last){
if(first<last){
int mid=(first+last)/2;
mergeSort(a,tempArray,first,mid);
mergeSort(a,tempArray,mid+1,last);
int i=first,j=first,k=mid+1;
while(j<=mid&&k<=last){
if(a[j].compareTo(a[k])>0){
tempArray[i++]=a[k++];
}else{
tempArray[i++]=a[j++];
}
}
while(i<=last&&j<=mid){
tempArray[i++]=a[j++];
}
while(i<=last&&k<=last){
tempArray[i++]=a[k++];
}
for(i=0;i<=last;i++){
a[i]=tempArray[i];
}
}
}
}
//迭代版本递归排序
public class Interation_MergeSort {
/**
* By ke_yi_
* @param a
*/
public static <T extends Comparable<? super T>>
void merge_Sort(T[] a){
int i,j;
T[] tempArray=(T[]) new Comparable<?>[a.length];
for(i=2;i<a.length;i=i<<1){
for(j=0;j*i<a.length;j++){
mergeSort(a,tempArray,i*j,i*(j+1));
}
}
mergeSort(a,tempArray,0,i);
}
public static <T extends Comparable<? super T>>
void mergeSort(T[] a, T[] tempArray, int first, int last) {
int i=first,j=first,mid=(first+last)/2;
int k=mid;
mid=mid>a.length?a.length:mid;
last=last>a.length?a.length:last;
while(j<mid&&k<last){
if(a[j].compareTo(a[k])>0){
tempArray[i++]=a[k++];
}else{
tempArray[i++]=a[j++];
}
}
while(j<mid){
tempArray[i++]=a[j++];
}
while(k<last){
tempArray[i++]=a[k++];
}
for(i=first;i<last;i++){
a[i]=tempArray[i];
}
}
}
时间复杂度:O(n*lgn)最好、最坏、平均都是
空间复杂度:O(n)需要使用2n的空间