开发者

List.Sort and Bubble Sort, which is faster? (Closed)

For example, I have a List

 List<int> list = new List<int>();

 list.Add(1);
 list.Add(5);
 list.Add(7);
 list.Add(3);
 list.Add(17);
 list.Add(10);
 list.Add(13);
 list.Add(9);
  1. I use List.Sort method like this

    private static int Compare(int x, int y)
    {
            if (x == y)
            开发者_StackOverflow社区    return 0;
            else if (x > y)
                return -1;
            else
                return 1;
    }
    List.Sort(Compare);
    
  2. I use bubble sort like this

     private static void Sort(List<int> list)
     {
        int size = list.Capacity;
        for (int i = 1; i < size; i++)
        {
             for (int j = 0; j < (size - i); j++)
             {
               if (list[j] > list[j+1])
               {
                  int temp = list[j];
                  list[j] = list[j+1];
                  list[j+1] = temp;
                }
             }
        }
    }
    

My question like the title, I wonder that which is faster?

Thank you


On the whole, bubble sort will be slower than almost anything else, including List.Sort which is implemented with a quick sort algorithm.


Bubble sort is simple to implement, but it's not very efficient. The List.Sort method uses QuickSort, which is a more complex and also more efficient algorithm.

However, when you have very few items in your list, like in your example, the efficiency of the algorithm doesn't really matter. What matters is how it's implemented and how much overhead there is, so you would just have to use the Stopwatch class to time your examples. This will of course only tell you which is faster for the exact list that you are testing, so it's not very useful for choosing an algorithm to use in an application.

Besides, when there are very few items in the list, it doesn't really matter which algorithm is faster because it takes so little time anyway. You should consider how much items there will be in the actual implementation, and if the number of items will grow over time.


Have a look at the documentation of List<T>.Sort():

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.

Since bubble sort is O(n ^ 2) (both on average and in the worst case), you can expect List<T>.Sort() to be (much) faster on large data sets. The speed of sorting 8 elements (as you have) is usually so minuscule (even using bubble sort), that it doesn't matter what you use.

What could affect the speed in this case is the fact that you use a delegate with List<T>.Sort(), but not with your bubble sort. Invoking delegates is relatively slow, so you should try to avoid them if possible when you are micro-optimizing (which you shouldn't do most of the time).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜