What's the most elegant way to bubble-sort in C#?

后端 未结 10 1892
旧巷少年郎
旧巷少年郎 2020-12-06 03:33

Can this be cleaned up?

using System;  
class AscendingBubbleSort 
{     
    public static void Main()
    {
        int i = 0,j = 0,t = 0;
        int []c=         


        
10条回答
  •  孤街浪徒
    2020-12-06 03:58

    I believe there is an improvement in the answer proposed by Jon Skeet. After each loop, the number of iterations should exclude the last item processed in the previous iteration. So, here's the code:

    public void BubbleSortImproved(IList list)
    {
        BubbleSortImproved(list, Comparer.Default);
    }
    
    public void BubbleSortImproved(IList list, IComparer comparer)
    {
        bool stillGoing = true;
        int k = 0;
        while (stillGoing)
        {
            stillGoing = false;
            //reduce the iterations number after each loop
            for (int i = 0; i < list.Count - 1 - k; i++)
            {
                T x = list[i];
                T y = list[i + 1];
                if (comparer.Compare(x, y) > 0)
                {
                    list[i] = y;
                    list[i + 1] = x;
                    stillGoing = true;
                }
            }
            k++;
        }
    }
    

提交回复
热议问题