优点:对于已经有序或接近有序的数组很快
public class InsertSort {
private static void insertSort(int[] a) {
//前n行有序要循环比较n-1次
for (int x = 1; x < a.length; x++) {
for (int y = x; y > 0; y--) {
if (a[y - 1] > a[y]) {
int temp = a[y - 1];
a[y - 1] = a[y];
a[y] = temp;
continue;
}
break;
}
}
}
public static void main(String[] args) {
int[] array = {8, 78, 23, 4, 251, 73, 51, 87, 3};
insertSort(array);
for (int i : array) {
System.out.print(i + " ");
}
}
}