插入排序的關鍵思想是每次將後端未排序序列的第一個元素插入到前面已經有序的序列中,而且在插入過程當中須要與比當前「大」的元素交換位置。插入排序總的交換次數等於原始輸入序列的逆序數。簡易實現及測試用例以下:java
import java.util.logging.Handler; public class Insertion { private static void exch(Comparable[] a, int i, int j) { Comparable tmp = a[i]; a[i] = a[j]; a[j] = tmp; } private static boolean less(Comparable a, Comparable b) { return (a.compareTo(b) < 0); } private static void show(Comparable[] a) { int N = a.length; for (int i = 0; i < N; i++) { System.out.print(a[i] + " "); } System.out.println(); } public static boolean isSorted(Comparable[] a) { int N = a.length; for (int i = 1; i < N; i++) { if (less(a[i], a[i - 1])) return false; } return true; } public static void sort(Comparable[] a) { int N = a.length; for (int i = 0; i < N; i++) { for (int j = i; j > 0 && less(a[j], a[j - 1]); j--) { exch(a, j, j - 1); } } } public static void main(String[] args) { String[] a = StdIn.readAllStrings(); Selection.sort(a); show(a); } }