最近从网易公开课在看麻省理工学院的公开课《算法导论》,感觉还不错,接下来几篇文章所示学习日记了,不准备对算法细节做过多描述,感兴趣的可以自己去看。

文章分几篇讲经典排序算法,直接上代码,根据结果对算法性能有个直观了解。本篇先说插入排序(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     }
Insertion sort

相关文章:

  • 2021-07-21
  • 2022-02-25
  • 2021-04-04
  • 2021-12-30
  • 2021-08-30
猜你喜欢
  • 2021-12-15
  • 2021-11-27
  • 2021-12-12
  • 2021-06-16
  • 2021-05-02
  • 2021-04-04
相关资源
相似解决方案