递归实现过程
- 第一次排序
- 将数组第二个数和第一个数进行比较,如果第二个数小的话就放到第一个数前面
- 第一次排序结束后排好的部分就有两个数了、
- 下一次排序就从第三个数开始往前判断即可
- 之后的while循环排序
- 判断当前数和前面的数的大小
- 如果当前数小的话就换位置到前面,只要找到一个数比当前数更小就停止循环(因为排好序的部分可以保证前面的部分都会比当前数小了)
- while循环结束后
- 将索引index++,指向数组下一个位置的数。如果没到数组末尾的话,就讲数组和index传入函数进行递归
递归实现代码
import java.util.Arrays;
public class InsertSort {
public static void main(String[] args) {
int[] arr = new int[]{2,9,4,7,3,3,6,5};
System.out.println("排序前数组:\t\t" + Arrays.toString(arr));
insertSort(arr, 1);
System.out.println("排序完成后数组:\t" + Arrays.toString(arr));
}
public static void insertSort(int[] arr, int index) {
int temp = 0;
int p = index;
while (p >= 0) {
if (arr[p] < arr[p-1]) {
temp = arr[p-1];
arr[p-1] = arr[p];
arr[p] = temp;
} else {
break;
}
p--;
}
index++;
if (index == arr.length-1) {
return;
}
insertSort(arr, index);
}
}