public void Sort ( Comparison<T> comparison )
This method uses System.Array.Sort, which uses the QuickSort algorithm. This implementation
performs an unstable sort; that is, if two elements are equal, their order might not be
preserved.In contrast, a stable sort preserves the order of elements that are equal.On average, this method is an O(n log n) operation, where n is Count; in the worst case it is
an O(n ^ 2) operation.
我们可以看到此算法采用快速排序(QuickSort algorithm),快速排序算法是指选取一个元素,按算法比它小的放在前边排成
一个队列,比它大的在后边排成一个队列.然后再排前边和后边的队列.最后使之排成一个有序的队列.我们看下边的代码1using System;
2using System.Collections.Generic;
3
4public class Example
5}
我们简单的将List的元素按照从小到大排列.单步跟踪Sort排序,我们获取x和y以及返回值如下:
x y return
(1) 1 4 -1
(2) 4 4 0
(3) 4 3 1
(4) 2 4 -1
(5) 4 4 0
(6) 4 2 1
(一)这里应该是以4为标准比较,之后变为1 3 2 4
(7) 1 3 -1
(8) 3 3 0
(9) 3 2 1
(二)这里应该是以3为标准比较,之后变为1 2 3 4
(10)1 1 0
(11)1 2 -1
(三)这里应该是以2为标准比较,之后变为1 2 3 4
(12)1 1 0
红色表示比较后还没有排序的元素问题如下:
1.为什么每次比较都要比较一次自身呢?如第(5),(8),(10),(12).如果没有这些自身比较,速度不是应该更快吗?我想应该
有更合理的解释.
2.看步懂第(5)和(6),这两步为什么会有呢?
希望达人能给小菜鸟解答一下.