Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
冒泡排序未给出正确的结果代码,附加C#?_C#_.net_Sorting - Fatal编程技术网

冒泡排序未给出正确的结果代码,附加C#?

冒泡排序未给出正确的结果代码,附加C#?,c#,.net,sorting,C#,.net,Sorting,我的排序代码没有给出正确的结果它没有正确排序给定的列表当我没有得到错误时请检查它 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+

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

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

}
static void Main(字符串[]args)
{
列表a=新列表(新int[]{3,7,6,1,8,5});
内部温度;
//foreach(a中的int i)

for(int i=1;i您发布的不是的实现。您忘记了循环,而不再交换任何数字。下面是编写的冒泡排序实现。
仍在进行
检查是您的实现中至少缺少的:

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;
            }
        }
    }
}
publicsvoidbubblesort(IList列表);
{
BubbleSort(列表,Comparer.Default);
}
public void BubbleSort(IList列表、IComparer比较器)
{
bool-stillGoing=true;
虽然(仍在进行)
{
仍然继续=错误;
对于(int i=0;i0)
{
列表[i]=y;
列表[i+1]=x;
仍然继续=正确;
}
}
}
}

我无法理解您的代码,也不懂C。但无论如何,这是冒泡排序的排序逻辑(用C编写)

//假设数组a[]中有n个元素

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

这不是代码审查网站。如果你没有被验证,不要尝试编写已经编写了数百万次的代码。使用现有的工具,在谷歌上查看你的代码是否正确地对输入排序。但是
控制台。WriteLine
调用are与此无关。@Damain如果你还在看这个,我必须写代码的输出-注意,如果数组已经排序,就不会发生交换。但是你的
控制台.WriteLine
调用在交换发生的块内。因此,如果数组已经排序,你将不会得到输出。相反,在后面有一个单独的循环在当前元素中,通过数组循环并对每个元素执行
Console.WriteLine
//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;
            }
        }
    }