[英]Problem with mergesort algorithm in C#
this code should work like merge sort algorithm but it doesnt work and gives the output 0 instead of sorting numbers,whats the problem friends?thanks 这段代码应该像合并排序算法一样工作,但是它不起作用并且给出输出0而不是对数字进行排序,这是什么问题的朋友?谢谢
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++;
}
while (x > nums.Length){
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;
}
For getting your output completely, try 为了完全获得输出,请尝试
string merge="";
foreach(var n in nums2)
merge+=n.ToString() + " ";
textBox4.Text = merge;
(ok, this can be done faster / nicer / fancier using Linq & String.Join, or a StringBuilder, but for testing purposes this should be enough). (好的,这可以使用Linq&String.Join或StringBuilder更快/更好/更出色地完成,但是出于测试目的,这已经足够了)。
Perhaps this does not solve all the problems with your code above, but it will probably help you to debug it easier. 也许这不能解决上面代码的所有问题,但可能会帮助您更轻松地调试它。
The line 线
if (y > nums1.Length-1)
Should not be inside 不应在里面
if (x > nums1.Length-1)
because you want to test for each of those conditions. 因为您要测试每个条件。 If you exit your first
while
loop because x >= nums.Length - 1
, you want to ensure you've run y
through to the end as well. 如果由于
x >= nums.Length - 1
while
退出第一个while
循环, x >= nums.Length - 1
确保也将y
一直运行到最后。
The logic is much easier achievable through LINQ 通过LINQ可以轻松实现逻辑
var numA = new int[]{...};
var numB = new int[]{...};
var result = numA.Union(numB).OrderBy(num => num); // add .Distinct() if you like
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.