基本思想:每一步将一个待排序的数据插入到前面已经排好序的有序序列中,直到插完所有元素为止。
代码:
import java.util.Arrays;
public class InsertSort {
public static void main(String[] args) {
int arr[] = {102, 25, 35, 24, 17};
System.out.println("原始数组");
System.out.println(Arrays.toString(arr));
for (int i = 1; i < arr.length; i++) {
//定义要插入的数
int insertNum = arr[i];
//定义要插入数的前面那一个数的索引
int indexFrontNum = i- 1;
while (indexFrontNum >= 0 && insertNum < arr[indexFrontNum]) {
//如果满足循环条件,说明第二个比第一个小,所以先将第二个的值变为第一个
arr[indexFrontNum + 1] = arr[indexFrontNum];
indexFrontNum--;
}
//退出while循环,说明已经找到最小的值,这时候需要将indexFrontNum+1索引位置
// (因为while循环结束时indexFrontNum--了,原来indexFrontNum这个位置就是要放的最小值的位置)上的值=最初要插入的数
arr[indexFrontNum + 1] = insertNum;
System.out.println("第" + (i) + "轮插入");
System.out.println(Arrays.toString(arr));
}
}
}