List的Sort()排序的疑问

我们看下List的Sort排序的函数为
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{
 6    private static int CompareDinos(int x, int y)
 7    {
 8        if (x < y)
 9            return -1;
10        else if (x == y)
11            return 0;
12        else
13            return 1;
14    }

15
16    public static void Main()
17    {
18        List<int> dinosaurs = new List<int>();
19        dinosaurs.Add(1);
20        dinosaurs.Add(4);
21        dinosaurs.Add(2);
22        dinosaurs.Add(3);
23        Display(dinosaurs);
24
25        Console.WriteLine("\nSort with generic Comparison<int> delegate:");
26        dinosaurs.Sort(CompareDinos);
27        Display(dinosaurs);
28
29        Console.ReadKey();
30    }

31
32    private static void Display(List<int> list)
33    {
34        Console.WriteLine();
35        foreach (int s in list)
36        {
37            Console.WriteLine("\"{0}\"", s);
38        }

39    }

40}

我们简单的将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),这两步为什么会有呢?
希望达人能给小菜鸟解答一下.

posted @ 2007-04-23 11:10  Kuffy Wang  阅读(3923)  评论(6编辑  收藏  举报