简单的冒泡排序c#

Kar*_* O. 26 c# arrays sorting bubble-sort

int[] arr = {800,11,50,771,649,770,240, 9};

int temp = 0;

for (int write = 0; write < arr.Length; write++)
{
    for (int sort = 0; sort < arr.Length - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }       
    }   
    Console.Write("{0} ", arr[write]);  
}
Run Code Online (Sandbox Code Playgroud)

我试图做的就是使用这个数组进行简单的冒泡排序.我想弄清楚为什么排序搞砸了.例如,这里的数组是{800,11,50,771,649,770,240, 9}:

以下是显示的内容: 11, 50, 649, 9, 649, 770, 771, 800

我想我可能会在比较中遗漏一些东西.

Mat*_*ten 69

不,您的算法有效,但您的Write操作在外部循环中放错了位置.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

  • 对于那些建议我写的人来说错了,谢谢!这就是导致事情搞砸的原因.现在它有效 (3认同)

azu*_*eca 8

这个对我有用

public static int[] SortArray(int[] array)
{
    int length = array.Length;

    int temp = array[0];

    for (int i = 0; i < length; i++)
    {
        for (int j = i+1; j < length; j++)
        {
            if (array[i] > array[j])
            {
                temp = array[i];

                array[i] = array[j];

                array[j] = temp;
            }
        }
    }

    return array;        
}
Run Code Online (Sandbox Code Playgroud)

  • 它不是[冒泡排序](https://en.wikipedia.org/wiki/Sorting_algorithm#Bubble_sort)。来自维基百科:“该算法从数据集的开头开始。它比较前两个元素,如果第一个大于第二个,则交换它们。**它继续对每对相邻元素执行此操作数据集的末尾。**然后它再次从前两个元素开始,重复直到最后一次没有发生交换。” (2认同)

小智 6

public static void BubbleSort(int[] a)
    {

       for (int i = 1; i <= a.Length - 1; ++i)

            for (int j = 0; j < a.Length - i; ++j)

                if (a[j] > a[j + 1])


                    Swap(ref a[j], ref a[j + 1]);

    }

    public static void Swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
Run Code Online (Sandbox Code Playgroud)

  • 清晰且自我记录的代码不需要注释. (13认同)
  • 请不要只发布代码.解释你在向我们展示什么. (7认同)