第一章 算法概念
1.1 算法插入排序的伪代码:
INSERTION-SORT(A)
1  for j ← 2 to length[A]
2       do key ← A[j]
3          ▹ Insert A[j] into the sorted sequence A[1 ‥ j - 1].
4          i ← j - 1
5          while i > 0 and A[i] > key
6              do A[i + 1] ← A[i]
7                 i ← i - 1
8          A[i + 1] ← key
Java实现:
import java.util.Comparator;public class InsertionSort {
public static <T> void insertionSort(T[] t, Comparator<? super T> comparator) {
for (int j = 1; j < t.length; j++) {
T key = t[j];
int i = j - 1;
while (i > -1 && comparator.compare(t[i], key) > 0) {
t[i + 1] = t[i];
i--;
}
t[i + 1] = key;
}
} public static void main(String[] args) {
Integer[] ints = new Integer[] { 31, 41, 59, 26, 41, 58 }; System.out.println("before InsertionSort:");
for (int i : ints)
System.out.print(i + " ");
System.out.println(); insertionSort(ints, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1.intValue() - o2.intValue();
}
}); System.out.println("result:");
for (int i : ints)
System.out.print(i + " ");
System.out.println();
}
}
其中insertionSort是实现插入排序伪代码的函数,main是测试用的。
输出:
before InsertionSort:
31 41 59 26 41 58 
result:
26 31 41 41 58 59 coding后感
1,伪代码的数组下标是从1到数组长度的,而Java的数组下标是从0到数组长度减1的。改写虽然没有难度,但是请看伪代码的第5行“while i > 0”,i从大到小,等于0为止,多么的优雅?!,而我的Java代码,不得不改成“while (i > -1”,感觉难看得多。而且,最外层循环“for (int j = 1”,也容易让Java新手产生误解,以为是从被排序数组的第一项开始循环的。
2,伪代码如果仅仅用Java实现一下而已的话,将是一件很容易的事儿,可能这本《算法导论》的Java实现,也有别的人在做吧。我想做的事是把Java的特性也融合进伪代码中。比方说这个插入排序,在伪代码中排序的是一个数组,而数组的元素是可以进行值判断的(大于小于等于),在Java中已经定义过的java.util.Comparator接口,正是给排序用的。我的函数的参数里有这个接口,而实现这个接口交给外部的调用函数,这个做法使这个函数更通用,可以直接用在各种场合。当然这个插入排序本身是没有任何实用价值的。1.2  算法分析
这一小节没有代码,就不另起段落了。我看了插入排序的算法分析后的感想是,和同样是Θ(n^2)的排序相比,插入排序的比较次数是一样的(平均情况和最坏情况都是),但是它赋值的次数,却可能是最多的。