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

后端 未结 10 1838
旧巷少年郎
旧巷少年郎 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:56

    The most elegant way to sort in C# is

    Array.Sort( object[] )
    

    That will work everywhere except in homework problems where the teacher asked you to implement the non-elegant bubble sort algorithm. ;-)

    0 讨论(0)
  • 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<T>(IList<T> list)
    {
        BubbleSortImproved<T>(list, Comparer<T>.Default);
    }
    
    public void BubbleSortImproved<T>(IList<T> list, IComparer<T> 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++;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 03:59

    I personally prefer this:

    string foo [] = new string[] {"abc", "def", "aaa", "feaf", "afea" };
    Array.Sort(foo);
    

    But that's just me. Sort is a solved problem, why reinvent the wheel?

    0 讨论(0)
  • 2020-12-06 04:12

    Overall, there's nothing wrong with your bubble sort implementation. If I were doing a real code review, I'd make the following changes:

    Choose more descriptive variable names

    Why is your array just called c?

    Minimize variable scope

    All of your variables are declared at the top of the function. Unless this is a homework requirement or a coding standard, its more idiomatic to declare variables "close" to the location where they are used, preferably so they have the smallest amount of scope possible.

    So, eliminate the first line which reads int i = 0,j = 0,t = 0;. Declare loop counters inline:

    for(int i = 0; i < 20; i++)
    

    And declare your temp variable in the place where its used:

                    Console.WriteLine("c[{0}]={1}, c[{2}]={3}", i, c[i], j, c[j]);
                    int t=c[i];
                    c[i]=c[j];
                    c[j]=t;
    

    Eliminate hard-coded array bounds.

    This:

    for(i=0;i<20;i++)
    

    Becomes this:

    for(i = 0; i < c.Length; i++)
    
    0 讨论(0)
提交回复
热议问题