插入排序思想:插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据;
插入排序图解:
插入排序代码:
//迭代版本
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