插入排序对少量元素的排序是很有效的。伪代码:
INSERTION-SORT(A)
for j = 2 to A.length
key = a[j]
// Insert A[j] into the sorted sequence A[1..j - 1]
while i > 0 and A[i] > key
A[i+1] = A[i]
i = i -1
A[i + 1] = key
private static int[] insertSort(int[] nums) {
if (nums.length <= 1) {
return nums;
}
for (int j = 1; j < nums.length; j++) {
int key = nums[j];
int i = j - 1;
while (i >= 0 && nums[i] > key) {
nums[i + 1] = nums[i];
i--;
}
nums[i+1] = key;
}
return nums;
}