最近从网易公开课在看麻省理工学院的公开课《算法导论》,感觉还不错,接下来几篇文章所示学习日记了,不准备对算法细节做过多描述,感兴趣的可以自己去看。
文章分几篇讲经典排序算法,直接上代码,根据结果对算法性能有个直观了解。本篇先说插入排序(insertion sort)。
(一)算法实现
1 protected void sort(int[] toSort) { 2 if (toSort.length <= 1) { 3 return; 4 } 5 for (int i = 1; i < toSort.length; i++) { 6 if (toSort[i] < toSort[i - 1]) { 7 int j = i; 8 int temp = toSort[i]; 9 while (j > 0 && temp < toSort[j - 1]) { 10 toSort[j] = toSort[j - 1]; 11 j--; 12 } 13 toSort[j] = temp; 14 } 15 } 16 }