/**
* 插入排序,时间复杂度:O(n2)
* @author neu_fufengrui@163.com
*
*/
public class InsertSort {
private InsertSort(){}
/**
* 普通插入排序
* @param a
* @param off
* @param len
*/
public static void sort(int a[], int off, int len){
for(int i = off+1; i <= len; i++){
if(a[i] < a[i-1]){
//记录值
int temp = a[i];
//查找位置
int j = off;
for(; j < i; j++){
if(a[j] <= a[i]){
continue;
}else{
break;
}
}
//移动
for(int k = i; k >= j && (k-1 >= off); k--){
a[k] = a[k - 1];
}
//归位
a[j] = temp;
}
print(a);
}
}/*output~.~
11,31,12,5,34,30,26,38,36,18,
11,12,31,5,34,30,26,38,36,18,
5,11,12,31,34,30,26,38,36,18,
5,11,12,31,34,30,26,38,36,18,
5,11,12,30,31,34,26,38,36,18,
5,11,12,26,30,31,34,38,36,18,
5,11,12,26,30,31,34,38,36,18,
5,11,12,26,30,31,34,36,38,18,
5,11,12,18,26,30,31,34,36,38,
*/
/**
* 带哨兵的插入排序
* @param a
* @param off
* @param len
*/
public static void sort1(int a[], int off, int len){
for(int i = off+1; i <= len; i++){
if(a[i] < a[i-1]){
//记录值
int temp = a[i];//哨兵
//移动
int k = i;
for(; (k-1 >= off) && a[k-1] >= temp; k--){
a[k] = a[k - 1];
}
//归位
a[k] = temp;
}
print(a);
}
} /*output~.~
11,31,12,5,34,30,26,38,36,18,
11,12,31,5,34,30,26,38,36,18,
5,11,12,31,34,30,26,38,36,18,
5,11,12,31,34,30,26,38,36,18,
5,11,12,30,31,34,26,38,36,18,
5,11,12,26,30,31,34,38,36,18,
5,11,12,26,30,31,34,38,36,18,
5,11,12,26,30,31,34,36,38,18,
5,11,12,18,26,30,31,34,36,38,
*/
/**
* 希尔排序
* 现将整个待排序序列分成若干字序列,对子序列中进行直接插入排序,
* 整个序列基本有序的时候,再对全体序列进行一次插入排序
*
* 关键是增量的确定,时间复杂度小于O(n2)
*
* 这个示例选择增量为5,3,1
*/
public static void sort2(int a[], int off, int len){
//待完善
}
public static void print(int a[]){
for(int i : a){
System.out.print(i+",");
}
System.out.println();
}
public static void main(String[] args) {
int a[] = {11, 31, 12, 5, 34, 30, 26, 38, 36, 18};
InsertSort.sort(a, 0, a.length-1);//普通插入排序
InsertSort.sort1(a, 0, a.length-1);//带哨兵的插入排序
}
}