思想:對未排序的数据执行逐个插入到前面已排好的位置
package utils;
public class InsertSort {
static final int SIZE = 10;
static void insertS(int[] a) {
int i, j, t;
for (i = 1; i < a.length; i++) {
t = a[i];
j = i - 1;
while (j >= 0 && t < a[j]) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = t;
System.out.print("第" + i + "结果:");
for (int k = 0; k < a.length; k++) {
System.out.print(" " + a[k]);
}
System.out.print("\n");
}
}
public static void main(String[] args) {
int[] shu = new int[SIZE];
int i;
for (i = 0; i < SIZE; i++) {
shu[i] = (int) (100 + Math.random() * (100 + 1));
System.out.print(" " + shu[i]);
}
System.out.print("\n");
insertS(shu);
System.out.print("over--");
}
}
?
|