将一个元素在已排好序的数组里选择合适的位置插入。
若将数组的第一个元素作为最初已排序部分,则可以对一个数组进行排序。
public int[] insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {//循环从第二个数组元素开始,因为arr[0]作为最初已排序部分
int temp = arr[i];//temp标记为未排序第一个元素
int j = i - 1;
while (j >= 0 && arr[j] > temp) {//将temp与已排序元素比较大小,寻找temp应插入的位
arr[j + 1] = arr[j]; //比temp大则向后移动
j--;
}
arr[j + 1] = temp;
}
return arr;
}
直接插入排序。