插入排序

package com.victor.sort.algorithms;

import java.util.ArrayList;

import com.victor.sort.seeds.*;

/**
 * 插入排序
 * @author 黑妹妹牙膏
 *
 */
public class Insertion extends SortAlgorithms {

	/*
	Algorithm
	for i = 2:n,
	    for (k = i; k > 1 and a[k] < a[k-1]; k--) 
	        swap a[k,k-1]
	    → invariant: a[1..i] is sorted
	end
	
	Properties
	■Stable 
	■O(1) extra space 
	■O(n2) comparisons and swaps 
	■Adaptive: O(n) time when nearly sorted 
	■Very low overhead 
	
	Discussion
	Although it is one of the elementary sorting algorithms with O(n2) worst-case time, insertion sort is the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the problem size is small (because it has low overhead). 

	For these reasons, and because it is also stable, insertion sort is often used as the recursive base case (when the problem size is small) for higher overhead divide-and-conquer sorting algorithms, such as merge sort or quick sort. 
	*/
	
	@Override
	protected ArrayList<Integer> doSort(ArrayList<Integer> Alist) {
		ArrayList<Integer> a = Alist;
		int n = a.size();
		int k;
		for(int i=1;i<n;i++)
		{
			int temp = a.get(i);
			for(k=i;k>0 && temp<(a.get(k - 1));k--)
			{
				a.set(k, a.get(k-1));       
			}
			a.set(k,temp);
			moveMentIncrease();
		}
		return a;
	}

	@Override
	public String getName() {
		return "Insertion";
	}
	
	public static void main(String[] args)
	{
		Seeds seed1 = new Random();
//		Seeds seed2 = new NearSorted();
//		Seeds seed3 = new Reversed();
//		Seeds seed4 = new FewUniqueKeys();
		SortAlgorithms SA = new Insertion();
		SA.sort(seed1,20);
		SA.print();
//		SA.sort(seed2,10000);
//		SA.sort(seed3,10000);
//		SA.sort(seed4,10000);
	}
}


转载于:https://my.oschina.net/readjava/blog/304437

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值