排序------插入排序

插入排序(InsertionSort)

定义:对数组的插入排序将数组分为两部分,第一部分是有序的,初始时只含有数组的第一项。第二部分含有其余的项。进行插入排序时,从未排序部分移走第一项,并将它插入有序部分中合适的有序位置。

如图:

                                       

<1>迭代插入排序

public class InsertionSort {
	public static <T extends Comparable<? super T>> void InsertionSort(T[]a,int first,int last) {
		for(int unsorted = first+1;unsorted<last;unsorted++) {
			//保存下一个非顺序的值
			T nextToInsert =a[unsorted];
			//将该值插入
			insertInorder(nextToInsert, a, first, unsorted-1);
		}
	}
	
	private static <T extends Comparable<? super T>> void insertInorder(T anEntry,T[] a,int begin,int end) {
		int index = end;	//有序部分最后一项的下标
		while((index>=begin)&&(anEntry.compareTo(a[index])<0)) {
			//腾空间
			a[index+1]=a[index];
			index--;
		}
		a[index+1]=anEntry;
	}
	public static void main(String[] args) {
		Integer[] a = {9,8,7,6,5,4,3,2,1};
		InsertionSort.InsertionSort(a, 0, 9);
		for(Integer integer:a) {
			System.out.println(integer);
		}
	}
}

<2>递归插入排序

public class Recursion {
	public static <T extends Comparable<? super T>> void InsertionSort(T[] a,int first,int last) {
		if(first<last) {
			InsertionSort(a,first,last-1);
			insertInOrder(a[last],a,first,last-1);
		}
	}
	private static <T extends Comparable<? super T>> void insertInOrder(T anEntry,T[] a,int begin,int end) {
		//将anEntry插入有序数组中
		if(anEntry.compareTo(a[end])>=0) {
			a[end+1]=anEntry;//将插入项放到最后项后面
		}else if(begin<end) {
			//将有序部分最后项后移一位,继续判断
			a[end+1]=a[end];
			insertInOrder(anEntry,a,begin,end-1);
		}else {
			//当begin==end && anEntry<a[end]
			a[end+1]=a[end];
			a[end]=anEntry;
		}
	}
	public static void main(String[] args) {
		Integer[] a = {9,8,7,6,5,4,3,2,1};
		Recursion.InsertionSort(a, 0, a.length-1);
		for(Integer integer:a) {
			System.out.println(integer);
		}
		
	}


}

插入排序的效率:

    最优时插入排序是O(n)的,最坏时是O(n*n)的。数组越接近有序,插入排序要做的工作越少。

对于n项数组,first是0,last是n-1,则for循环执行n-1次,所以方法insertInorder被调用n-1次。insertInorder中,begin是0且end是0~n-2,每次调用该方法,insertInorder内的循环执行总次数为:1+2+....(n-1),故插入排序是O(n*n)的。


猜你喜欢

转载自blog.csdn.net/qq_41304534/article/details/80720108