繁体   English   中英

两个列表框之间的冒泡排序未排序和排序 c#

[英]bubble sort between two listboxes unsorted and sorted c#

我创建了一个具有两个列表框(未排序和排序)的表单,当我单击按钮冒泡排序时,它出现在未排序的列表框中,但现在想要单击另一个按钮进行排序,并在排序的列表框中以正确的顺序对它们进行排序和清除未排序的列表框。

我是编程新手,所以很难理解编码。 我用谷歌搜索了我需要的东西,但似乎找不到明确的答案。

我的代码如下:

这会将它添加到我的未排序列表框中:

int[] myNumbers = { 5, 1, 8, 9, 15 };

lstunsorted.Items.Add(5);
lstunsorted.Items.Add(1);
lstunsorted.Items.Add(8);
lstunsorted.Items.Add(9);
lstunsorted.Items.Add(15); 

这就是我在排序按钮下的移动和排序:

        for (int intCount = lstunsorted.SelectedItems.Count - 1; intCount >= 0; intCount--)
        {
            lstsorted.Items.Add(lstunsorted.SelectedItems[intCount]);
            lstunsorted.Items.Remove(lstunsorted.SelectedItems[intCount]);
        }

        int[] arr = { 5, 1, 8, 9, 15 };
        int temp = 0;
        for (int i = 0; i < arr.Length; i++)
        {
        for (int J = 0; J < arr.Length; J++)
        {
        if (arr[i] > arr[J])
        {
                        temp = arr[i];

                        arr[i] = arr[J];

                        arr[J] = temp;
                    }
                }
            }

任何帮助将不胜感激,并以初学者格式解释,让我了解发生了什么。

ListBox.Items是一个无类型的集合,这意味着您可以向它添加任何类型的值,字符串、int 等等。 这使得使用起来相当麻烦,因此第一步应该是将其转换为常规数组或列表。

var myArray =  lstunsorted.Items.Cast<int>().ToArray();

.Cast<int>()将列表中的每个项目转换为一个 int。 这仅在项目实际上是整数时才有效,但在您的情况下它很好(否则请参阅.OfType<T>() )。 .ToArray()获取所有值并将它们放入一个新数组中。

然后,您将对项目进行排序,我认为这是练习的重点。 如果没有,可以用

Array.Sort(myArray );

最后一步是更新列表框。

lstsorted.Items.Clear();
foreach(var i in myArray )
{
    lstsorted.Items.Add(i);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM