冒泡排序在c中使用数组,用户可以输入数字

本文关键字:用户 输入 数字 数组 冒泡排序 | 更新日期: 2023-09-27 18:29:33

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

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; }
}

冒泡排序在c中使用数组,用户可以输入数字

您应该首先从用户那里获得数字,然后对它们进行排序。现在,InputStudent函数什么都不做——它只接受一个整数作为参数,用用户的值重新赋值,然后退出。

相反,你可以做这样的事情来从用户那里获得一个int数组:

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