插入排序有两种插入方式,一种是在原数组上进行排序,第二种是新建一个数组进行插入排序,其原理都是一样的,这个地方记录的是原数组上进行排序的方式
```
import java.util.Arrays;
// 插入排序
// 插入排序,先实现小范围有序,再实现大范围有序,时间复杂度最复杂为o(n2),最好的情况只需要执行n次
public class InsertSort {
public static void main(String[] args) {
int[] toSortArr = {4,5,1,2,3};
// 当长度小于二时,直接返回原数组
if(toSortArr.length < 2) {
return;
}
// 从i~n实现数组排序
for(int i = 1; i < toSortArr.length; i++) {
for(int j = i - 1; j >= 0 && toSortArr[j+1] < toSortArr[j]; j--) {
// 交换
swap(toSortArr, j+1,j);
}
}
System.out.println(Arrays.toString(toSortArr));
}
public static void swap(int[] arr, int i, int j) {
// 交换方式1
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
```