算法思想
- 访问每一个元素
- 将每一个元素插入到已经有序的数组中适当的位置
- 为了给要插入的元素腾出空间,需要将其余所有元素在插入之前都向右移动一位
Java实现
public class Insertion {
// 将a[]按升序排列
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = 1; i < N; i++) {
// 将a[i]插入到a[i-1]、a[i-2]、a[i-3]...之中
for (int j = i; j > 0 && less(a[j], a[j - 1]); j--)
exch(a, j, j - 1);
}
}
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
// 在单行中打印数组
public static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
// 测试数组元素是否有序
public static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i - 1])) return false;
return true;
}
}
public class Test {
public static void main(String[] args) {
String[] test = {"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"};
Insertion.sort(test);
assert Insertion.isSorted(test);
Insertion.show(test);
}
}
A E E L M O P R S T X