优点:对于已经有序或接近有序的数组很快
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 + " ");
}
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。