[英]Bubble sort for Listbox not working C#
I have a program where the user can input number into a listbox the user also gets and option to sort the listbox. 我有一个程序,用户可以在其中输入用户也可以得到的列表框中输入数字,并可以对列表框进行排序。 I am not allowed to use any arrays or containers or list, just modify the items listbox property and use converting and parsing. 我不允许使用任何数组或容器或列表,只需修改项目列表框属性并使用转换和解析即可。 I want to do this through a bubble sort, although the numbers that only displays on the listbox once the sort button is clicked is 0,1,2,3,4... 我想通过气泡排序来做到这一点,尽管单击排序按钮后仅在列表框中显示的数字是0、1、2、3、4 ...
private void sorted()
{
int a = Convert.ToInt32(lstHoldValue.Items.Count);
int temp = Convert.ToInt32(lstHoldValue.Items[0]);
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++)
{
if (Convert.ToInt32(lstHoldValue.Items[i]) > Convert.ToInt32(lstHoldValue.Items[j]))
{
temp = Convert.ToInt32(lstHoldValue.Items[i]);
(lstHoldValue.Items[i]) = Convert.ToInt32(lstHoldValue.Items[j]);
(lstHoldValue.Items[j]) = temp;
}
}
}
lstHoldValue.Items.Clear();
for (int i = 0; i < a; i++)
{
Convert.ToInt32(lstHoldValue.Items.Add("\t" + i));
}
}
How users enter values to the listbox 用户如何向列表框中输入值
private void btnAdd_Click(object sender, EventArgs e)
{
string text = "\t" + txtInitialise.Text;
if (this.index < MAX_ITEMS) // MAX_ITEMS or 10
{
Convert.ToInt32(lstHoldValue.Items.Count);
int dnum;
if (int.TryParse(txtInitialise.Text, out dnum))
{
Convert.ToInt32(lstHoldValue.Items.Add( "\t" + dnum));
index++;
txtInitialise.Text = "";
Seems like you are just adding the index of the List item to List, that's the reason it always returning 0 - 4 (5 elements). 似乎您只是将List项目的索引添加到List,这就是它总是返回0-4(5个元素)的原因。 Updated the answer to sort only using the list items. 将答案更新为仅使用列表项进行排序。
Updated: 更新:
Maximum items allowed to insert into listbox: 允许插入列表框的最大项目数:
const int MAX_ITEMS = 10;
Your sorted method was working correctly, though you cleared the listbox in the end, so you lose the sorting, as swapping is done inside the listbox using the for-loop: 尽管最后清除了列表框,但排序后的方法仍能正常工作,因此您失去了排序功能,因为使用for循环在列表框内进行了交换:
private void sorted()
{
int a = Convert.ToInt32(lstHoldValue.Items.Count);
int temp = Convert.ToInt32(lstHoldValue.Items[0]);
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++)
{
if (Convert.ToInt32(lstHoldValue.Items[i]) > Convert.ToInt32(lstHoldValue.Items[j]))
{
temp = Convert.ToInt32(lstHoldValue.Items[i]);
(lstHoldValue.Items[i]) = "\t" + Convert.ToInt32(lstHoldValue.Items[j]);
(lstHoldValue.Items[j]) = "\t" + temp;
}
}
}
}
Add button click: 单击添加按钮:
private void btnAdd_Click(object sender, EventArgs e)
{
int index = 0;
if (index < MAX_ITEMS) // MAX_ITEMS set to 10
{
int dnum;
if (int.TryParse(txtInitialise.Text, out dnum))
{
lstHoldValue.Items.Add("\t" + dnum);
index++;
txtInitialise.Text = "";
}
}
}
Sort button click: 排序按钮单击:
private void btnSort_Click(object sender, EventArgs e)
{
sorted();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.