在要排序的一组数中,假设前面的n-1个数已经试排好顺序的。 现在要把第n个数插到前面的有序数中,使得这n个数也是排好顺序的。如此反复循环,直到全部排好顺序。
public class InsertSort {
// 从小到大插入排序
static void Insert(int a[]) {
int temp = 0;
for (int i = 1; i < a.length; i++) {
int j = i - 1;
temp = a[i];// 将要插入的数
for (; j >= 0 && temp < a[j]; j--) {
a[j + 1] = a[j];// 将大于temp的值整体后移一个单位
}
a[j + 1] = temp;
}
}