代碼實現(JAVA):
/**
* 打印數組內容
* @param a
*/
public static void saymsg(int[] src) {
for (int i = 0; i < src.length; i++) {
System.out.print(src[i]);
System.out.print(" ");
}
System.out.println();
}
/**
* 直接插入排序
*/
private static void insertSort(int[] src) {
int temp = 0;
for (int i = 1; i < src.length; i++) {
int j = i - 1;
temp = src[i];
for (; j >= 0 && temp < src[j]; j--) {
src[j + 1] = src[j];
}
src[j + 1] = temp;
System.out.println("第"+i+"次排序:");
saymsg(src);
}
saymsg(src);
}
public static void main(String[] args) {
int[] src = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 };
System.out.println("原始數組排序:");
saymsg(src);
insertSort(src);
}
圖片來自維基百科
更多建議: