插入排序的时间复杂度是:常数阶
插入排序:
1.把数一个一个插入
2.如果插入的数小于插入之前的数,就和前一个数就行替换,一直替换到第一个或者前一个数比 他小
3.找到最小的数之后,把他插入到最小的下标里面去
public class InsertSort {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 9, 5, 6, -1};
insertSort(arr);
//测试花费的时间
int array[] = new int[200000];
for (int i = 0; i < 200000; i++) {
array[i] = (int) (Math.random() * 800000);
}
//开始时间
long time = new Date(System.currentTimeMillis()).getTime();
insertSort(array);
//结束时间
long time2 = new Date(System.currentTimeMillis()).getTime();
System.out.println((time2 - time) + "毫秒");
}
//排序算法
public static void insertSort(int[] arr) {
int insertValue = 0;
int insertIndex = 0;
for (int i = 1; i < arr.length; i++) {
//插入的数
insertValue = arr[i];
//插入的数的下标的前一个下标
insertIndex = i - 1;
//下标不能小于0并且如果插入的数要比前一个数小
while (insertIndex >= 0 && insertValue < arr[insertIndex]) {
//前后两个数进行交互
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
//判断是否发生了变化
if (insertIndex + 1 != i) {
//退出的时候把插入下标的值,赋值给找到的排序前一个的下标再加一
arr[insertIndex + 1] = insertValue;
}
// System.out.println("第"+i+"轮的结果是");
// System.out.println(Arrays.toString(arr));
}
}
}