冒泡排序和foreach索引
本文关键字:索引 foreach 冒泡排序 | 更新日期: 2023-09-27 18:00:23
下面有一些按钮点击事件的代码,它使用了冒泡排序。我有点不清楚使用。尝试按升序对数组进行排序顺序此外,我必须使用前臂,并且需要从中获取索引。尝试int z=a.GetEnumerator();不起作用。int k=0//作弊以获得代码工作
int k = 0;//Cheat to get code working
foreach (BankAccount BankAccount in a)
//for (int i = 0; i < a.Length; i++)
{
//int z = a.GetEnumerator();
lstBefore.Items.Add(a[k].show());
k += 1;//Cheat to get code working
}
//if (a[0] is IComparable)
//{
//Sort.BubbleSort(a);//Sort a
k = 0;//Cheat to get code working
for (int i = 0; i < a.Length; i++)
{
lstAfter.Items.Add(a[k].show());
//else MessageBox.Show("unable to sort");
k += 1;//Cheat to get code working
}
//}
//else MessageBox.Show("unable to sort");
class Sort : IComparable
{
public static void BubbleSort(IComparable[] arr)
{
bool swap = true;
IComparable temp;
for (int i = 0; swap; i++)
{
swap = false;
for (int j = 0; j < (arr.Length - (i + 1)); j++)
{
//int test = arr[j].CompareTo(arr[j + 1]);
if (arr[j].CompareTo(arr[j + 1]) > 0)
//If this balance is < than next balance
{
temp = (IComparable)arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swap = true;
}
}
}
}
}
我还有
public class BankAccount : IComparable, IComparable<BankAccount>//Class BackAccount - //Icomarable
{
private decimal balance;
private string FullName;
//...
public int CompareTo(BankAccount that)//Compare To
{
if (this.balance > that.balance) return -1;//If this balance is > than next balance
if (this.balance == that.balance) return 0;//If this balance is = to next balance
return 1;//If this balance is < than next balance
//return this.balance.CompareTo(that.balance);
}
}
Thanks,
看起来您只需要在Sort
类(而不仅仅是BankAccount
类)中实现CompareTo
。
首先,foreach
无论如何都没有索引。如果需要索引,请使用for循环
其次,Sort
类没有实现IComparable
(这导致了错误)。这是一个比较器,而不是比较。如果您愿意,它可以实现IComparer
,或者是静态的
当你有Array.Sort
或List.Sort
方法时,你为什么要深入到冒泡排序实现中,它实现了QuickSort,而且肯定更快更好?我会避免这样做的。