int[] arr = {1, 52, 12, 36, 45};

// 插入排序
insertSort(arr);


//插入排序
private static void insertSort(int[] arr) {
if (arr == null || arr.length <= 1) {
return;
}
int current;
for (int i = 0; i < arr.length - 1; i++) {
current = arr[i + 1];
int preIndex = i;
while (preIndex > 0 && current < arr[preIndex]) {
// 给位置 将前一位数据给当前的数,因为要多插入一位但是放在哪,是不知道的,所以preIndex + 1就是位置
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
;
//当找到的时候
arr[preIndex+1] = current;

}
System.out.println(Arrays.toString(arr));

}
posted on 2021-07-13 11:22  沐雨清晨  阅读(24)  评论(0编辑  收藏  举报