【发布时间】:2010-12-18 07:43:41
【问题描述】:
我想写合并排序算法,当我调试程序并给它数字时,它会出现索引超出范围错误,我的代码有什么问题?提前谢谢。
private void button3_Click(object sender, EventArgs e)
{
string[] source = textBox1.Text.Split(',');
string[] source1 = textBox3.Text.Split(',');
int[] nums2 = new int[source1.Length + source.Length];
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])///it gives out of range on this line
{
nums2[z] = nums[x];
x++;
}
else
{
nums2[z] = nums1[y];
y++;
}
z++;
}
if (x > nums.Length)
{
while (y <= nums1.Length)
{
nums2[z] = nums1[y];
z++;
y++;
}
if (y > nums1.Length)
{
while (x <= nums.Length)
{
nums2[z] = nums[x];
z++;
x++;
}
}
}
string merge = nums2[z].ToString();
textBox4.Text = merge;
}
}
【问题讨论】:
标签: c# winforms algorithm mergesort