【问题标题】:Problem with output of mergesort algorithm归并排序算法的输出问题
【发布时间】:2010-12-18 15:45:39
【问题描述】:

这段代码给出了输出,但它有一个问题是当用户在 textbox1 中写入 5,6 和在 textbox3 中写入 7,8 时,它输出 5,6。我知道问题是当数组的元素结束时,它没有打印其他数组的其余元素,我评论了问题行。

已编辑:我使用 textbox1 和 textbox3 来获取用户想要合并的数组元素

private void button3_Click(object sender, EventArgs e)
{


    string[] source = textBox1.Text.Split(',');
    string[] source1 = textBox3.Text.Split(',');
    int[] nums2 = new int[8];
    int[] nums = new int[source.Length];
    for (int i = 0; i < source.Length; i++)
    {
        nums[i] = Convert.ToInt32(source[i]);

    }
    int[] nums1 = new int[source1.Length];
    for (int j = 0; j < source1.Length; j++)
    {
        nums1[j] = Convert.ToInt32(source1[j]);
    }
    int x = 0;
    int y = 0;
    int z = 0;

    while (x < nums.Length && y < nums1.Length)
    {
        if (nums[x] < nums1[y])
        {
            nums2[z] = nums[x];
            x++;

        }
        else
        {
            nums2[z] = nums1[y];
            y++;
        }

        z++;
    }////----->>it works untill here

    while (x > nums.Length)///this mean when the elements of nums end,out the rest of the elements in other textbox but it doesnt do anything,whats the problem ?
    {
        if (y <= nums1.Length)
        {
            nums2[z] = nums1[y];

            z++;
            y++;
        }
    }
    while (y > nums1.Length)
    {

        if (x <= nums.Length)
        {
            nums2[z] = nums[x];
            z++;
            x++;
        }
    }
        string merge = "";
        foreach (var n in nums2)
            merge += n.ToString() + ",";
        textBox4.Text = merge;


    }

【问题讨论】:

  • 合并排序,文本框,你在说什么?合并排序中没有臭的 texbox!
  • 我使用 textbox1 和 textbox3 来获取用户想要合并的数组元素
  • 不,这并不比您之前重复的问题更清楚:stackoverflow.com/questions/4477248/…
  • @Cody Gray:在最后一个问题中,我的输出是 0,但现在我没有零

标签: c# mergesort


【解决方案1】:

做(删除你最后的时间)

while (x < nums.Length)
{
        nums2[z] = nums[x];
        z++;
        x++;
}

while (y < nums1.Length)
{
        nums2[z] = nums1[y];
        z++;
        y++;
}

因为您不知道保留了哪些数组项,所以您当前的代码无论如何也不起作用,因为 y 与 nums 和 vise verse 无关。

编辑:我将第一个 while 复制到第二个 while,修复它,删除最后一个 while 循环(2 个 while 和 if 在其中)并替换它。

【讨论】:

  • 最后一个 while 块应该使用 y 而不是 x 作为 nums1 的索引。
  • @arash,修复它,@BlueMonkMN,是的,我修复了它,我先复制粘贴而忘记了第二个循环的内容。
【解决方案2】:

while (x &gt; nums.Length)while (y &gt; nums1.Length) 上的两个条件都没有意义,因为这永远不会发生。

在前面的块中,您递增xy,只要它们小于 小于nums.Lengthnums1.Length。因此,它们永远不会变大(最多相等),因此两个条件都将始终为假,并且“剩余”项目不会被合并。

请注意,您的合并排序实现中还有其他问题,但我猜这不在您的具体问题的范围内。

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2019-10-11
    • 1970-01-01
    相关资源
    最近更新 更多