rusty Mole rusty Mole - 13 days ago 4
C# Question

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...

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 = "";

Answer

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). 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:

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();
}
Comments