算法描述:對於給定的一個數組,初始時假設第一個記錄自成一個有序序列,其余記錄為無序序列。接着從第二個記錄開始,按照記錄的大小依次將當前處理的記錄插入到其之前的有序序列中,直至最后一個記錄插入到有序序列中為止。
package sorting; /** * 插入排序 * 平均O(n^2),最好O(n),最壞O(n^2);空間復雜度O(1);穩定;簡單 * @author zeng * */ public class InsertionSort { public static void insertionSort(int[] a) { int tmp; for (int i = 1; i < a.length; i++) { for (int j = i; j > 0; j--) { if (a[j] < a[j - 1]) { tmp = a[j - 1]; a[j - 1] = a[j]; a[j] = tmp; } } } } public static void main(String[] args) { int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 }; insertionSort(a); for (int i : a) System.out.print(i + " "); } }