问题
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
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;
}
回答1:
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).
Perhaps this does not solve all the problems with your code above, but it will probably help you to debug it easier.
回答2:
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.
回答3:
- the logic is a mess. you shouldn't use 'nums2' to store result, i suggest you should use a better name.
- you assign num2 = new int[5] ? you should use something else if you don't know exact length. eg use List instead. Slower performance but its more suitable for small array sorting.
- int z = 0; is not a correct way to implement. if you have while loop and need increment counting, why don't you use for loop?
- in 'if' after 'while' you keep incrementing z without reset it to '0' it will index out of range
The logic is much easier achievable through LINQ
var numA = new int[]{...};
var numB = new int[]{...};
var result = numA.Union(numB).OrderBy(num => num); // add .Distinct() if you like
来源:https://stackoverflow.com/questions/4477248/problem-with-mergesort-algorithm-in-c-sharp