目录
1、需求
排序数组:int[] arr = {76,75,82,4,6,1,3,5,23,4,2,3,4,12,34,32};
2、思路
0~1 范围有序,往左边看,小了就换 和冒泡正好相反
0~2 范围有序,往左边看,小了就换
...
0~n 范围有序,以此类推,周而复始
3、代码
时间复杂度O()
import java.util.Arrays;
public class InsertSortCase {
public static void main(String[] args) {
int[] arr = {76,75,82,4,6,1,3,5,23,4,2,3,4,12,34,32};
insertSort(arr);
System.out.println(Arrays.toString(arr));
}
private static void insertSort(int[] arr) {
int length = arr.length;
if (arr == null || length < 2) {
return;
}
/**
* 0 ~ 1 有序
* 0 ~ 2
* 0 ~ 3
* ...
* 0 ~ length-1
*/
for (int i = 1; i < length; i++) {
for (int j = i - 1; j >= 0 && arr[j] > arr[j+1]; j--) {
swap(arr, j, j+1);
}
}
}
private static void swap(int[] arr, int i, int j) {
int tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
}
}