gpt4 book ai didi

c# - 在 C# 中冒泡排序最优雅的方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:42:40 24 4
gpt4 key购买 nike

这可以清理吗?

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

最佳答案

您粘贴的内容不是 bubble sort .这是一种“蛮力”排序,但不是冒泡排序。这是通用冒泡排序的示例。它使用任意比较器,但允许您省略它,在这种情况下,默认比较器用于相关类型。它将对 IList<T> 的任何(非只读)实现进行排序,其中包括数组。阅读上面的链接(指向维基百科)以更多地了解冒泡排序的工作原理。请注意我们如何从头到尾经历每个循环,但只将每个项目与其邻居进行比较。它仍然是 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;
}
}
}
}

关于c# - 在 C# 中冒泡排序最优雅的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1595244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com