package Sort;
import org.junit.Test;
/*
* 插入排序
* 时间复杂度:O(n^2) 由定理:N个互异数的数组的平均逆序数是 N(N-1)/4,可知:基于相邻元素之间的比较和交换的算法的时间复杂度的一个下界为O(N^2)
* 空间复杂度:O(1),只使用了一个中间变量
*
*/
public class InsertSort {
public static <T extends Comparable<? super T>> void insertSort(T[] a) {
for (int p = 1; p < a.length; p++) {
T tmp = a[p];// 保存当前位置p的元素,其中[0,p-1]已经有序
int j;
for (j = p; j > 0 && tmp.compareTo(a[j - 1]) < 0; j--) {
a[j] = a[j - 1];// 后移一位
}
a[j] = tmp;// 插入到合适的位置
}
}
@Test
public void testInsertSort() {
Integer[] arr = { 34, 8, 64, 51, 32, 21 };
insertSort(arr);
for (Integer i : arr) {
System.out.print(i + " ");
}
}
}