直接插入排序认为从索引i开始,i之前的元素都是有序的,把索引i处的元素和从索引i-1到0的元素依次进行比较,找到合适的位置,进行插入。
private static void insertSort(int[] array) {
if (array == null || array.length == 0) {
return;
}
int j;
for (int i = 1; i < array.length; i++) {
j = i;
while (j > 0 && array[j] < array[j - 1]) {
int tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = tmp;
j--;
}
}
}
网友评论