总结
/**
*
* 名称: 直接插入排序
* 时间复杂度: O(N^2) (逆序) / O(N) (有序)
* 空间复杂度: O(1)
* 稳定性: 稳定 (稳定的可以变成不稳定的, 不稳定的一定变不成稳定的)
* 结论: 数据越有序排序所消耗的时间越短
* 应用场景: 多用于比较有序的数据
*
*/
具体实现
public static void main(String[] args) {
int[] array = {5, 10, 8, 1, 16, 9};
InsertSort(array);
System.out.println(Arrays.toString(array));
}
public static void InsertSort(int[] arr){
int tmp = 0;
for (int i = 1; i < arr.length ; i++) {
tmp = arr[i];
for (int j = i - 1; j > -1;) {
if(tmp < arr[j]){ //在此处如果加入 <= 插入排序就会变成不稳定
arr[j+1] = arr[j];
j--;
arr[j+1] = tmp;
}else{
break;
}
}
}
}
运行结果截图
结论验证
//验证结论
// 情景一: 当给数组中插入完全有序的数据时
public static void main2(String[] args) {
int[] array = new int[10_0000];
for (int i = 0; i < array.length; i++) {
array[i] = i+1;
}
long startTime = System.currentTimeMillis();
InsertSort(array);
long endTime = System.currentTimeMillis();
System.out.println("当数据有序时使用直接插入排序所需要的时间:" + (endTime - startTime));
}
// 情景三: 当给数组中插入一些无序的数据时
public static void main3(String[] args) {
int[] array = new int[10_0000];
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(10_0000);
}
long startTime = System.currentTimeMillis();
InsertSort(array);
long endTime = System.currentTimeMillis();
System.out.println("当数据无序时使用直接插入排序所需要的时间:" + (endTime - startTime));
}
//由上可看出鲜明的对比,数据越有序排序所消耗的时间越短
main2执行截图
main3执行截图