-4

我的排序代码没有给出正确的结果它没有正确排序给定的列表,而我没有收到错误请检查它,

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

}
4

3 回答 3

2

我无法理解你的代码,我不知道 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

于 2012-04-06T08:01:59.057 回答
0

您发布的内容不是冒泡排序算法的实现。当没有数字被交换时,您忘记了循环。这是由 John Skeet编写的冒泡排序实现。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;
            }
        }
    }
}
于 2012-04-06T07:46:06.183 回答
0

从嵌套循环中删除 console.write。将 console.write 放在新的 for 循环或 foreach 中的嵌套循环之外。然后你会得到正确的顺序。否则冒泡排序的逻辑是正确的

于 2012-04-06T08:32:24.350 回答