直接插入排序
插入排序包括 直接插入排序, 折半插入排序, Shell排序
package com.longshine.arthmetic.sort;
import java.util.ArrayList;
import java.util.List;
import com.longshine.arthmetic.NumSortElement;
import com.longshine.arthmetic.SortElement;
//直接插入排序
/**
* 从第i项开始( 0<i<n)与第j项比较 0<=j<i;
* 若i项 < j项, j+1项~ i-1项向后移动一位
*
*/
public class InsertSort {
public static void main(String[] args){
int[] data = new int[] {5,8,1,20,15,13,7,6,30,45,3};
List<SortElement> lists = new ArrayList<SortElement>();
for (int d : data) {
lists.add(new NumSortElement(d,""));
}
lists.add(new NumSortElement(20,"*"));
System.out.println(lists);
new InsertSort().sort((List)lists);
System.out.println(lists);
}
//开始排序
public void sort(List<NumSortElement> datas){
for(int i = 1; i < datas.size(); i++){
for(int j = 0; j < i; j++){
int c = datas.get(i).compareTo(datas.get(j));
if( c < 0){
//插入j位置
//j位置~i -1的位置元素向后移动1位
NumSortElement tmpI = datas.get(i);
for(int k = i-1; k >= j; k--){
datas.set(k+1, datas.get(k));
}
datas.set(j, tmpI);
}
else if(c==0){
//为了证明它是稳定排序
//插入j + 1位置
//j+1位置~ i -1的位置元素向后移动1位
NumSortElement tmpI = datas.get(i);
for(int k = i-1; k >= j + 1; k--){
datas.set(k+1, datas.get(k));
}
datas.set(j+1, tmpI);
}
}
}
}
}
时间复杂度O(n2), 空间复杂度为O(1), 很好,没用上额外的空间