/**
* 直接插入排序
* 时间复杂度 O(n²)
* 空间复杂度 临时变量O(1)
*/
public class InsertDirectSort {
public static void main(String[] args) {
int[] b = {3, 1, 5, 4, 32, 6, 90, 48, 32, 78};
System.out.println(Arrays.toString(directInsertSort(b)));
}
private static int[] directInsertSort(int[] array) {
if (array == null || array.length == 0) {
return array;
}
for (int i = 1; i < array.length; i++) {
int j = i - 1; //当前已排序好的最后一个位置
int temp = array[i];// 先取出待插入数据保存,因为向后移位过程中会覆盖掉待插入数
while (j >= 0 && array[j] > temp) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp;// 找到比待插入数据小的位置,将待插入数据插入
}
return array;
}
}
输入:
{3, 1, 5, 4, 32, 6, 90, 48, 32, 78}
执行结果:
[1, 3, 4, 5, 6, 32, 32, 48, 78, 90]