本文介绍了mergesort算法的输出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这段代码给出了输出,但是它有一个问题,就是当用户在textbox1中写 5,6 而在textbox3中写 7,8 时,它给出的输出是5,6.
我知道问题在于,当数组的元素结束时,它不打印其他数组的其余元素,我在问题行中发表了评论.
*我使用textbox1和textbox3来获取用户要合并的数组的元素
This code gives output but it has one problem that is when user write 5,6 in textbox1 and 7,8 in textbox3 it gives output 5,6.
I know the problem is that when the elements of an array ends,it doesnt print the rest elements of other array, I commented on line of problem.
*I used textbox1 and textbox3 for getting the elements of the arrays that user wants to merge
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;
}
推荐答案
while (x < nums.Length)
{
nums2[z] = nums[x];
z++;
x++;
}
while (y < nums1.Length)
{
nums2[z] = nums1[y];
z++;
y++;
}
顺便说一句:不要忘记在开始合并之前确保对您的两个输入数组进行了排序.
BTW: Don''t forget to make sure that your two input arrays are sorted before starting the merge.
这篇关于mergesort算法的输出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!