C# 中最优雅的冒泡排序方式是什么?

发布于 2024-08-08 13:04:34 字数 918 浏览 4 评论 0原文

这个可以清理吗?

using System;  
class AscendingBubbleSort 
{     
    public static void Main()
    {
        int i = 0,j = 0,t = 0;
        int []c=new int[20];
        for(i=0;i<20;i++)
        {
            Console.WriteLine("Enter Value p[{0}]:", i);
            c[i]=int.Parse(Console.ReadLine());
        }
        // Sorting: Bubble Sort
        for(i=0;i<20;i++)
        {
            for(j=i+1;j<20;j++)
            {
                if(c[i]>c[j])
                {
                    Console.WriteLine("c[{0}]={1}, c[{2}]={3}", i, c[i], j, c[j]);
                    t=c[i];
                    c[i]=c[j];
                    c[j]=t;
                }
            }
        }
        Console.WriteLine("bubble sorted array:");
        // sorted array output
        for(i=0;i<20;i++)
        {
            Console.WriteLine ("c[{0}]={1}", i, c[i]);
        }
    }
}

Can this be cleaned up?

using System;  
class AscendingBubbleSort 
{     
    public static void Main()
    {
        int i = 0,j = 0,t = 0;
        int []c=new int[20];
        for(i=0;i<20;i++)
        {
            Console.WriteLine("Enter Value p[{0}]:", i);
            c[i]=int.Parse(Console.ReadLine());
        }
        // Sorting: Bubble Sort
        for(i=0;i<20;i++)
        {
            for(j=i+1;j<20;j++)
            {
                if(c[i]>c[j])
                {
                    Console.WriteLine("c[{0}]={1}, c[{2}]={3}", i, c[i], j, c[j]);
                    t=c[i];
                    c[i]=c[j];
                    c[j]=t;
                }
            }
        }
        Console.WriteLine("bubble sorted array:");
        // sorted array output
        for(i=0;i<20;i++)
        {
            Console.WriteLine ("c[{0}]={1}", i, c[i]);
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

过期以后 2024-08-15 13:04:34

您粘贴的内容不是冒泡排序。这是一种“蛮力”排序,但不是冒泡排序。这是通用冒泡排序的示例。它使用任意比较器,但允许您省略它,在这种情况下,默认比较器用于相关类型。它将对 IList 的任何(非只读)实现进行排序,其中包括数组。阅读上面的链接(维基百科)以更多地了解冒泡排序的工作原理。请注意我们如何从开始到结束执行每个循环,但仅将每个项目与其邻居进行比较。它仍然是 O(n2) 排序算法,但在许多情况下它会比您给出的版本更快。

public void BubbleSort<T>(IList<T> list)
{
    BubbleSort<T>(list, Comparer<T>.Default);
}

public void BubbleSort<T>(IList<T> list, IComparer<T> comparer)
{
    bool stillGoing = true;
    while (stillGoing)
    {
        stillGoing = false;
        for (int i = 0; i < list.Count-1; 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;
            }
        }
    }
}

What you've pasted there isn't a bubble sort. It's a sort of "brute force" sort but it's not bubble sort. Here's an example of a generic bubble sort. It uses an arbitrary comparer, but lets you omit it in which case the default comparer is used for the relevant type. It will sort any (non-readonly) implementation of IList<T>, which includes arrays. Read the above link (to Wikipedia) to get more of an idea of how bubble sort is meant to work. Note how on each loop we go through from start to finish, but only compare each item with its neighbour. It's still an O(n2) sort algorithm, but in many cases it will be quicker than the version you've given.

public void BubbleSort<T>(IList<T> list)
{
    BubbleSort<T>(list, Comparer<T>.Default);
}

public void BubbleSort<T>(IList<T> list, IComparer<T> comparer)
{
    bool stillGoing = true;
    while (stillGoing)
    {
        stillGoing = false;
        for (int i = 0; i < list.Count-1; 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;
            }
        }
    }
}
远山浅 2024-08-15 13:04:34

C# 中最优雅的排序方式是,

Array.Sort( object[] )

它在任何地方都适用,除了老师要求你实现不优雅的冒泡排序算法的家庭作业问题。
;-)

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.
;-)

风为裳 2024-08-15 13:04:34

总的来说,您的冒泡排序实现没有任何问题。如果我正在进行真正的代码审查,我会进行以下更改:

选择更具描述性的变量名称

为什么您的数组被称为c

最小化变量范围

所有变量都在函数顶部声明。除非这是作业要求或编码标准,否则更惯用的做法是将变量声明为“靠近”它们使用的位置,最好使它们具有尽可能小的范围。

因此,删除第一行 int i = 0,j = 0,t = 0;。内联声明循环计数器:

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

并在使用它的地方声明临时变量:

                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;

消除硬编码数组边界。

这:

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

变成这样:

for(i = 0; i < c.Length; i++)

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++)
深陷 2024-08-15 13:04:34

大多数人不会费心让冒泡排序变得优雅。不过,总的来说,我发现这样做:

for (int i = 0; i < items.Length; i++) {
    Item item = items[i];
    // do something with item
}

比这样做更优雅,也更易于维护:

Item item;
int i;
for (i = 0; i < items.Length; i++) {
    item = items[i];
    // do something with item
}

换句话说,在最小的适用范围内声明变量。否则,您可能会发现自己在代码中的其他位置使用 iitem 执行某些操作,然后在不应该使用的地方再次使用它们。

Most people would not bother making a bubble sort elegant. In general, though, I find that doing this:

for (int i = 0; i < items.Length; i++) {
    Item item = items[i];
    // do something with item
}

is both more elegant and more maintainable than doing this:

Item item;
int i;
for (i = 0; i < items.Length; i++) {
    item = items[i];
    // do something with item
}

In other words, declare your variables within the smallest applicable scope. Otherwise you might find yourself doing something with i or item at some other point in the code and then using them again where you shouldn't be.

夏夜暖风 2024-08-15 13:04:34
  • 我将使用交换方法来交换两个数组项。
    (如何编写交换方法的详细信息留作家庭作业!)

  • 你应该考虑当项目已经按顺序排列时的情况

  • 你应该阅读插入排序以获得更多分数:-)

  • 而不是从键盘读取测试数据,看看您是否可以学习如何使用nUnit

  • I would use a swap methed to swap the two array items.
    (details of how to write swap method left as homework!)

  • You should think about the case when the items are already in order

  • You should read up on Insertion sort for more marks :-)

  • Rather then reading the test data from the keyboard, see if you can learn how to use nUnit

是伱的 2024-08-15 13:04:34

我个人更喜欢这个:

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

但这就是我。排序已经解决了问题,为什么要重新发明轮子呢?

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?

用心笑 2024-08-15 13:04:34

我相信答案提出了改进乔恩·斯基特。每次循环后,迭代次数应排除上一次迭代中处理的最后一项。所以,这是代码:

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++;
    }
}

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++;
    }
}
梦里梦着梦中梦 2024-08-15 13:04:34
int[] array = {4,5,7,1,8};           

int n1, n2;
bool stillgoing = true;

while (stillgoing)
{
    stillgoing = false;
    for (int i = 0; i < (array.Length-1); i++)
    {                  
        if (array[i] > array[i + 1])
        {
            n1 = array[i + 1];
            n2 = array[i];

            array[i] = n1;
            array[i + 1] = n2;
            stillgoing = true; 
        }
    }
}
for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine(array[i]);
}

从 Jon skeet 那里得到了一些想法......

int[] array = {4,5,7,1,8};           

int n1, n2;
bool stillgoing = true;

while (stillgoing)
{
    stillgoing = false;
    for (int i = 0; i < (array.Length-1); i++)
    {                  
        if (array[i] > array[i + 1])
        {
            n1 = array[i + 1];
            n2 = array[i];

            array[i] = n1;
            array[i + 1] = n2;
            stillgoing = true; 
        }
    }
}
for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine(array[i]);
}

Took some ideas from Jon skeet...

堇年纸鸢 2024-08-15 13:04:34
    public int[] BubbleSortInAesc(int[] input)
    {
        for (int i = input.Length; i > 0; i--)
        {
            for (int j = 0; j < i-1; j++)
            {
                if (input[j] > input[j + 1])
                {
                    //Swap the numbers
                    input[j] = input[j + 1]+input[j];
                    input[j + 1] = input[j] - input[j + 1];
                    input[j] = input[j] - input[j + 1];
                }
            }
        }
        return input;
    }
    public int[] BubbleSortInAesc(int[] input)
    {
        for (int i = input.Length; i > 0; i--)
        {
            for (int j = 0; j < i-1; j++)
            {
                if (input[j] > input[j + 1])
                {
                    //Swap the numbers
                    input[j] = input[j + 1]+input[j];
                    input[j + 1] = input[j] - input[j + 1];
                    input[j] = input[j] - input[j + 1];
                }
            }
        }
        return input;
    }
深海蓝天 2024-08-15 13:04:34

我认为你的算法没问题,但我会将排序功能放在单独的类和方法中。

I think your algorithm in ok, but I would put the sort functionality in a seperate class and method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文