0

我正在尝试使用冒泡排序,在 c# 中从最小到最大排序数字,到目前为止我有什么问题?

private void Order_Click(object sender, EventArgs e) {
  value1 = Convert.ToInt32(textBox1.Text);
  value2 = Convert.ToInt32(textBox2.Text);
  value3 = Convert.ToInt32(textBox3.Text);
  value4 = Convert.ToInt32(textBox4.Text);
  value5 = Convert.ToInt32(textBox5.Text);

  int[] myarray = { value1, value2, value3, value4, value5 };
  int n = 0;
  bool swapped = true;
  int j = 0;
  int tmp;
  while (swapped) {
    swapped = false;
    j++;
    for (int i = 0; i < n - j; i++)
    {
      if (myarray[i] > myarray[i + 1]) {
        tmp = myarray[i];
        myarray[i] = myarray[i + 1];
        myarray[i + 1] = tmp;
        swapped = true;
        order1.Text = Convert.ToString(myarray[0] + "," + 
                                       myarray[1] + "," + 
                                       myarray[2] + "," + 
                                       myarray[3] + "," + 
                                       myarray[4]);
       }
     }
   }
 }
4

3 回答 3

1

您的代码有问题的第一件事是:

for (int i = 0; i < n - j; i++)

您的检查i < n - j将永远不会让控件通过循环。因为您已将 n 初始化为 0 并且 j 为 1(在 j++ 之后),所以i 不会小于 then -1,因此您的循环将无法按预期工作。由于您将 swapped 设置为 false,因此控件将退出 while 循环,因此不会进行排序。

您需要将代码更改为:

  while (swapped)
            {
                swapped = false;
                for (int i = 0; i < myarray.Length - 1; i++)
                {
                    if (myarray[i] > myarray[i + 1])
                    {
                        int t = myarray[i];
                        myarray[i] = myarray[i + 1];
                        myarray[i + 1] = t;
                        swapped = true;
                        Console.WriteLine(Convert.ToString(myarray[0] + "," + myarray[1] + "," + myarray[2] + "," + myarray[3] + "," + myarray[4]));
                    }

                }

            }
于 2012-07-30T20:22:47.587 回答
0

nj 变量似乎是不必要的。离开nj退出你的程序,并在你的 for 循环中,执行以下操作:

 for (int i = 0; i < (array1.Length - 1); i++)
于 2012-07-30T20:20:12.553 回答
-2

冒泡排序

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("Here comes the sorted array:");
        // Print the contents of the sorted array
        for(i=0;i<20;i++)
        {
            Console.WriteLine ("c[{0}]={1}", i, c[i]);
        }
    }
}

资源

于 2012-07-30T20:15:36.547 回答