插入排序是一种简单直观的排序算法,其工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
package com.example.datastructures.sort;
import java.util.Arrays;
/**
* @author maoyouhua
* @version jdk21
*
* 插入排序是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
* 插入排序在实现上通常采用in-place排序(即只需用到O(1)的额外空间的排序),
* 因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
*/
public class InsertSort {
/** 思路:从后往前遍历,前面部分已经是有序的,被插入数小于当前数即可
*
* @param arr 待排序数组
*/
private static void insertSort(int[] arr){
for (int i = 1; i < arr.length; i++) {
int insertValue = arr[i];
int insertIndex = i-1;
while (insertIndex >= 0 && insertValue < arr[insertIndex]){
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
arr[insertIndex + 1] = insertValue;
System.out.println("第"+ i +"轮输入");
System.out.println(Arrays.toString(arr));
}
}
/**
* 排序效率测试
* 花费时间是:681毫秒
*/
private static void efficiencyTest(){
int capacity = 80000;
int[] arr = new int[capacity];
for (int i = 0; i < capacity; i++) {
arr[i] = (int)(Math.random() * 100 * capacity);
}
long start = System.currentTimeMillis();
insertSort(arr);
long end = System.currentTimeMillis();
System.out.println("花费时间是:" + (end - start) + "毫秒");
}
/**
* 第1轮输入
* [3, 17, 15, 14, 1, 9]
* 第2轮输入
* [3, 15, 17, 14, 1, 9]
* 第3轮输入
* [3, 14, 15, 17, 1, 9]
* 第4轮输入
* [1, 3, 14, 15, 17, 9]
* 第5轮输入
* [1, 3, 9, 14, 15, 17]
*/
public static void main(String[] args) {
int[] arr = {17, 3, 15, 14, 1, 9};
insertSort(arr);
efficiencyTest();
}
}