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