gpt4 book ai didi

c# - 归并排序问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:35:58 26 4
gpt4 key购买 nike

我正在制作各种排序算法的菜单,现在我陷入了归并排序。单击执行按钮后遇到错误。我在 TextBox1 中输入了 5 个数字,在 TextBox2 中输入了另一组 5 个数字。它说索引超出了数组的范围。我在代码上指出了它出现的位置。有什么想法吗?

    private void ExeButton_Click(object sender, EventArgs e)
{
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
string[] numsInString1 = EntNum1.Text.Split(' ');
for (int j = 0; j < numsInString.Length; j++)
{
a[j] = int.Parse(numsInString[j]);
}
for (int j = 0; j < numsInString1.Length; j++)
{
b[j] = int.Parse(numsInString1[j]);
}
{
sortArray();
Display();
}

}

public void sortArray()
{
m_sort(0, 10 - 1);
}

public void m_sort(int left, int right)
{
int mid;

if (right > left)
{
mid = (right + left) / 2;
m_sort(left, mid);
m_sort(mid + 1, right);

merge(left, mid + 1, right);
}
}

public void merge(int left, int mid, int right)
{
int i, left_end, num_elements, tmp_pos;

left_end = mid - 1;
tmp_pos = left;
num_elements = right - left + 1;

while ((left <= left_end) && (mid <= right))
{
if (a[left] <= a[mid]) //index was outside the bounds of the the array
{
b[tmp_pos] = a[left];
tmp_pos = tmp_pos + 1;
left = left + 1;
}
else
{
b[tmp_pos] = a[mid];
tmp_pos = tmp_pos + 1;
mid = mid + 1;
}
}

while (left <= left_end)
{
b[tmp_pos] = a[left];
left = left + 1;
tmp_pos = tmp_pos + 1;
}

while (mid <= right)
{
b[tmp_pos] = a[mid];
mid = mid + 1;
tmp_pos = tmp_pos + 1;
}

for (i = 0; i < num_elements; i++)
{
a[right] = b[right];
right = right - 1;
}
}


private void ClearButton_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}

public void Display()
{
int i;
String numbers = "";
for (i = 0; i < 10; i++)
numbers += a[i].ToString() + " ";
numbers += b[i].ToString() + " ";
richTextBox1.AppendText(numbers + "\n");
}

最佳答案

关于您的具体问题:a 是一个包含 5 个元素的数组,索引为 0, 1, 2, 3, 4,所以 a[4] 是最后一个元素。您从 m_sort(0, 10 - 1) = m_sort(0, 9); 开始。在 m_sort() 中你计算

mid = (right + left) / 2 = (9 + 0) / 2 = 4

然后打电话

merge(left, mid + 1, right) = merge(0, 4 + 1, 9) = merge(0, 5, 9).

merge(int left, int mid, int right) 中你计算:

if (a[left] <= a[mid])   i.e.     if (a[0] <= a[5]) 

因此您访问了越界的 a[5]

我认为您的合并排序可以大大简化。您可能会查看 Web 上的许多资源或有关算法的教科书。

关于c# - 归并排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7227492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com