【问题标题】:Implementing Array into Bubblesort在冒泡排序中实现数组
【发布时间】:2020-06-24 02:24:14
【问题描述】:

稍后我一直试图找到在冒泡排序函数中使用此数组的方法,但由于某种原因在上下文中无法识别它,我想要做的就是找到一种方法来实现所有值将文本文件(数组)放入冒泡排序的变量 a 中。我尝试使用常规字符串数组来读取文本文件,但这被证明是不成功的,因为我无法在字符串数组上使用任何运算符。很高兴为我的任何替代解决方案提供任何帮助,我将非常感谢您的帮助。 :)

                    int[] a = { 3, 0, 2, 5, -1, 4, 1 };
                    int t;
                    Console.WriteLine("Original array :");
                    foreach (int aa in a)
                        Console.Write(aa + " ");
                    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;
                            }
                        }
                    }
                    Console.WriteLine("\n" + "Sorted array :");
                    foreach (int aa in a)
                        Console.Write(aa + " ");
                    Console.Write("\n");
                }
            }
        }
    }
}

【问题讨论】:

    标签: arrays algorithm sorting implementation


    【解决方案1】:
    else if (userAnswer == "1")
    {
        int[] a = { 3, 0, 2, 5, -1, 4, 1 };
        int t;
        Console.WriteLine("Original array :");
        foreach (int aa in a)
            Console.Write(aa + " ");
        for (int p = 0; p <= a.Length - 2; p++)
        {
            for (int i = p+1; i <= a.Length - 1; i++)
            {
                if (a[i] < a[p])
                {
                    t = a[i];
                    a[i] = a[p];
                    a[p] = t;
                }
            }
        }
        Console.WriteLine("\n" + "Sorted array :");
        foreach (int aa in a)
            Console.Write(aa + " ");
        Console.Write("\n");
    }
    

    您的排序代码应如上。 请注意,这是升序排序。

    【讨论】:

    • 啊,非常感谢!那么我最初的排序代码是降序的吗?我将如何获取我的数组并用数组值替换行:int[] a = { 3, 0, 2, 5, -1, 4, 1 }?
    • if (a[i] > a[p]) 把'if条件'改成降序排列。
    • 我将如何将数组从 for 循环添加到排序算法?它对示例集数字进行排序:3、0、2、5 等,但数组有 256 个数字我希望这个算法排序
    猜你喜欢
    • 2012-07-23
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2016-02-10
    相关资源
    最近更新 更多