归并排序

归并排序思想:将一个序列分成两半然后对两半分别排序,再将他们归并为一个有序序列。

归并排序图解:
 

归并排序的代码:(迭代版本代码由于写的急,没来的急优化,所以可读性不是很好)

//递归版本归并排序
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的空间 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值