【问题标题】:bubble sort in c# with array that user can input the numbersc#中的冒泡排序,用户可以输入数字的数组
【发布时间】:2014-11-06 22:31:43
【问题描述】:

我想让用户输入数字,然后用冒泡排序对其进行排序,但我没有找到正确的实现:/

class bubblesort
{
    static void Main(string[] args)
    {
        int[] a = new int[5];
        int t;

        for (int p = 0; p <= a.Length - 2; p++)
        {               
            for (int i = 0; i <= a.Length - 2; i++)
            {
                if (a[i] > a[i + 1])
                {
                    t = a[i + 1];
                    a[i + 1] = a[i];
                    a[i] = t;
                }

                InputStudent(a[i]);
            }               
        }

        Console.WriteLine("The Sorted array");

        foreach (int aa in a)
        {
            Console.Write(aa + " ");
        }

        Console.Read();
    }

    static void InputStudent(int p)
    {
        Console.WriteLine("Enter the Number");

        p = int.Parse(Console.ReadLine());
        Console.WriteLine();
    }

    public static int i { get; set; }
}

【问题讨论】:

  • 有什么问题?
  • 用户输入数字后输出排序数组 0 0 0 0 0 !
  • 为什么不先要求#s,然后进行排序?在排序中间请求 #s 真的没有意义。
  • 另外,您的输入学生函数似乎没有做任何事情。你传入一个 int,然后你从用户那里得到一个 int,然后你在方法内部做一个本地分配,一旦方法范围结束,它就会消失)
  • 我投票决定保持开放状态。这个问题问得不好,就其本身而言,我同意以“不清楚你在问什么”来结束,但答案很好。

标签: c# arrays algorithm sorting


【解决方案1】:

您应该首先从用户那里获取数字,然后您可以对它们进行排序。现在你的 InputStudent 函数没有做任何事情 - 它只是接受一个整数作为参数,用用户的值重新分配它,然后退出。

您可以改为执行以下操作从用户那里获取整数数组:

private static int[] GetIntArrayFromUser(int numberOfElementsToGet)
{
    var intArrayFromUser = new int[numberOfElementsToGet];

    for (int i = 0; i < numberOfElementsToGet; i++)
    {
        while (true)
        {
            // Prompt user for integer and get their response
            Console.Write("Enter an integer for item #{0}: ", i + 1);
            var input = Console.ReadLine();

            // Check the response with int.TryParse. If it's a valid int, 
            // assign it to the current array index and  break the while loop
            int tmpInt;
            if (int.TryParse(input, out tmpInt))
            {
                intArrayFromUser[i] = tmpInt;
                break;
            }

            // If we get here, we didn't break the while loop, so the input is invalid.
            Console.WriteLine("{0} is not a valid integer. Try again.", input);
        }
    }

    return intArrayFromUser;
}

然后你可以从 Main 调用这个方法来填充你的数组:

static void Main(string[] args)
{
    int[] a = GetIntArrayFromUser(5); // Get a five-element array

    // Insert your bubble-sort code here

    // Show the sorted array
    Console.WriteLine("The sorted array:");
    Console.WriteLine(string.Join(" ", a));

    Console.Read();
}

【讨论】:

    猜你喜欢
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2016-12-02
    • 2018-02-05
    相关资源
    最近更新 更多