Reputation: 3071
this code gives output but it has one problem that is when user write 5,6 in textbox1 and 7,8 in textbox3 it 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.
edited: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;
}
Upvotes: 1
Views: 218
Reputation: 22565
Do (remove your last while)
while (x < nums.Length)
{
nums2[z] = nums[x];
z++;
x++;
}
while (y < nums1.Length)
{
nums2[z] = nums1[y];
z++;
y++;
}
because you are not aware which array items remained, also your current code doesn't work anyway, because y is not related to nums and vise verse.
Edit: I copy past first while into second while, fix it, remove your last while loops (2 while with if in them) and replace this.
Upvotes: 1
Reputation: 60276
Both your conditions on while (x > nums.Length)
and while (y > nums1.Length)
don't make sense, since this will never happen.
In the block before, you increment x
and y
as long as they are smaller than nums.Length
or nums1.Length
. Therefore those will never become larger (at most equal), thus both conditions will always be false and the "remaining" items will not be merged in.
Note that there are other things wrong in your mergesort implementation, but that's not in the scope of your specific question I guess.
Upvotes: 1