插入排序
计算步骤
- 首先对数组的前两个数据进行从小到大排序。
- 接着将第三个数据与排好序的两个数据比较,将三个数据插入合适的位置。
- 然后,将第四个数据插入已排好序的前3个数据中。
- 不断重复上述过程,直到把最后一个数据插入合适的位置。最后,便完成了对原始数组从小到大的排序。
代码:
public class P4_3 {
static final int SIZE = 10;
public static void insertionSort(int[] a){
int i,j,t,h;
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.println();
}
}
public static void main(String[] args) {
int[] shuzu = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
shuzu[i] = (int)(100 + Math.random()*(100+1));
}
//
System.out.println("排序前数组为:");
for (int i = 0; i < shuzu.length; i++) {
System.out.print(" "+ shuzu[i]);
}
//
System.out.println();
insertionSort(shuzu);
System.out.println("排序后数组为:");
for (int i = 0; i < shuzu.length; i++) {
System.out.print(" "+ shuzu[i]);
}
}
}
结果
排序前数组为:
121 100 140 155 178 104 132 100 146 152
第1步排序结果 100 121 140 155 178 104 132 100 146 152
第2步排序结果 100 121 140 155 178 104 132 100 146 152
第3步排序结果 100 121 140 155 178 104 132 100 146 152
第4步排序结果 100 121 140 155 178 104 132 100 146 152
第5步排序结果 100 104 121 140 155 178 132 100 146 152
第6步排序结果 100 104 121 132 140 155 178 100 146 152
第7步排序结果 100 100 104 121 132 140 155 178 146 152
第8步排序结果 100 100 104 121 132 140 146 155 178 152
第9步排序结果 100 100 104 121 132 140 146 152 155 178
排序后数组为:
100 100 104 121 132 140 146 152 155 178
Process finished with exit code 0