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

后端 未结 10 1882
旧巷少年郎
旧巷少年郎 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 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++)
    

提交回复
热议问题