直接插入算法
基本思想:在要排序的一组数中,假设前面(n-1) [n>=2] 个数已经是排好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数也是排好顺序的。如此反复循环,直到全部排好顺序。
package sortalgorithm; public class StraightInsertionSort { public void insertSort() { int[] a = { 1, 3, 2, 4, 10, 7, 8, 9, 5, 6 }; int temp = 0; for (int i = 1; i < a.length; i++) { int j = i - 1; temp = a[i]; for (; j >= 0 && temp < a[j]; j--) { a[j + 1] = a[j]; } a[j + 1] = temp; System.out.println("第"+i+"次:"); for (int k = 0; k < a.length; k++) { System.out.print(a[k] + " "); } System.out.println(); } System.out.println("最终:"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } public static void main(String[] args) { StraightInsertionSort aa = new StraightInsertionSort(); aa.insertSort(); } }
运行结果: