/** * 算法策略:首先,将前两个数做比较,对这个两数进行排序;然后插入然后插入第三个数,对这个三个进行排序,一次类推。 * * @author *** * */ public class InsertSort { @SuppressWarnings({ "rawtypes", "unchecked" }) public static void insertSortMethodOne(Comparable[] data) { for (int i = 1; i < data.length; i++) { Comparable key = data[i]; int position = i; while (position > 0 && data[position - 1].compareTo(key) > 0) { data[position] = data[position - 1]; position--; } data[position] = key; } } public static void insertSortMethodTwo(int[] data) { for (int i = 1; i < data.length; i++) { int key = data[i]; int position = i; while (position > 0 && data[position - 1] > key) { data[position] = data[position - 1]; position--; } data[position] = key; } } @SuppressWarnings("rawtypes") public static void main(String[] args) { Comparable[] c = { 4, 9, 23, 1, 45, 27, 5, 2 }; int[] cArray = { 4, 9, 23, 1, 45, 27, 5, 2 }; insertSortMethodOne(c); insertSortMethodTwo(cArray); for (int i = 0; i < cArray.length; i++) System.out.println("插入排序:" + cArray[i]); System.out.println("==============================="); for (int i = 0; i < c.length; i++) System.out.println("插入排序:" + c[i]); } }