插入排序

插入排序思想:插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据;

插入排序图解:

插入排序代码:

//迭代版本
public class Interation_InsertSort {
	public static<T extends Comparable<? super T>> void I_insertionSort(T[] a,int first,int last){
		T firstUnsorted=null;
		for(int unsorted=first+1;unsorted<last;unsorted++){
			firstUnsorted=a[unsorted];
			insertInOrder(firstUnsorted,a,first,unsorted-1);
		}
	}
	private static<T extends Comparable<? super T>> void insertInOrder(T element,T[] a,int begin,int end){
		int index=end;
		while((index>=begin)&&(element.compareTo(a[index])<0)){
			a[index+1]=a[index];
			index--;
		}
		a[index+1]=element;
	}
}


 

//递归版本
public class Recursion_InsertSort {
	private static<T extends Comparable<? super T>> void R_insertionSort(T[] a,int first,int last){
		if(first<last){
			R_insertionSort(a,first,last-1);
			insertInOrder(a[last],a,first,last-1);
		}
	}
	private static<T extends Comparable<? super T>> void insertInOrder(T element,T[] a,int begin,int end){
		if(!(element.compareTo(a[end])<0)){
			a[end+1]=element;
		}else if(begin<end){
			a[end+1]=a[end];
			insertInOrder(element, a, begin, end-1);
		}else{
			a[end+1]=a[end];
			a[end]=element;
		}
	}
}

时间复杂度:O(n^2)

空间复杂度:n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值