排序过程
首先位置1上的数和位置0上的数进行比较,如果位置1上的数大于位置0上的数,将位置0上的数向后移一位,将1插入到0位置,否则不作任何处理。接下来每次插入的位置k依次和之前的数进行比较,找到属于自己的位置。
排序的各项指标
平均时间复杂度:O(N^2)
最坏时间复杂度:O(N^2)
空间复杂度:O(1)
是否稳定:稳定
排序实现
在这里插入代码片
public static void insertSort(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
for (int i = 1; i < arr.length; i++) {
for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1] ; j--) {
swap(arr, j, j + 1);
}
}
}
public static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}