气泡排序未给出附加 C# 的正确结果代码
本文关键字:结果 代码 排序 气泡 | 更新日期: 2023-09-27 18:30:26
我的排序代码没有给出正确的结果,当我没有收到错误时,它没有正确排序给定的列表,请检查一下,
static void Main(string[] args)
{
List<int> a = new List<int>(new int[] { 3, 7, 6, 1, 8, 5 });
int temp;
// foreach(int i in a)
for(int i=1; i<=a.Count; i++)
for(int j=0; j<a.Count-i; j++)
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
Console.WriteLine(a[j]);
}
Console.Read();
}
我无法理解您的代码,也不懂 C#。但无论如何,这里是气泡排序的排序逻辑(用 c 编写)。
//assuming there are n elements in the array a[]
for(i=0; i<n; i++)
{ for(j=1; j<n-i; j++)
{ if(a[j] < a[j-1])
{ temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
您也可以参考:www.sorting-algorithms.com/bubble-sort
您发布的内容不是气泡排序算法的实现。您忘记循环,而不再交换数字。这是John Skeet编写的Bubble Sort实现。stillGoing
检查是实现中至少缺少的内容:
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.Length-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;
}
}
}
}
从嵌套循环中删除 console.write。 将 console.write 放在嵌套循环之外的新 for 循环或 foreach。然后你会得到正确的顺序。否则,气泡排序的逻辑是正确的