在 C# 中进行冒泡排序最优雅的方法是什么? [英] What's the most elegant way to bubble-sort in C#?

查看:50
本文介绍了在 C# 中进行冒泡排序最优雅的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可以清理吗?

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]);
        }
    }
}

推荐答案

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

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

这篇关于在 C# 中进行冒泡排序最优雅的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆