插入排序
具体的执行步骤请详细看注释!!!
package com.yongjar.test;
/**
* @author yongjar
* @date 2021/3/2
* 插入排序
*/
public class InsertSort {
static final int SIZE = 10;
public static void insertionSort(int [] a) {
int t,j;
//a[0]=25 a[1] = 29,a[2]=21
for (int i = 0; i <a.length ; i++) {
// t = a[0] t = 25
// t = a[1] t=29
// t= a[2] t = 21
t = a[i];
// j = i-1, j = (0-1)=-1
// j = i-1 j=(1-1)=0
// j = i-1 j=(2-1)=1
j = i-1;
//j=-1 j>=0 =false
// j=0 j>=0 true && t(29)<a[0](25) false
// j=1 j>=0 true && t(21)<a[1](29) true continue
while(j>=0 && t<a[j]) {
//a[1+1] = a[1]; a[2] = a[1](29)
// a[0+1] = a[0] a[1] = a[0]25
a[j+1] = a[j];
// j-- 1--=0 ,返回执行while条件, j=0 j>=0 true && t(21) && t(21) < a[0]25 true
// j-- 0--=-1, 返回执行while条件, j=-1,false,结束while条件执行。
j--;
}
//a[-1+1]=25 a[0] = 25
//a[0+1] = 29
//a[-1+1] =21
a[j+1] = t;
System.out.println ("第" + 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[3];
shuzu[0] = 25;
shuzu[1] = 29;
shuzu[2] = 21;
System.out.print("排序前的数组为:\n");
System.out.print("\n");
insertionSort (shuzu);
System.out.print("排序后的数组为:\n");
for (int i = 0; i < 3; i++) {
System.out.print(shuzu[i] + " ");
}
System.out.println ();
}
}