0

バブルソートを使用するボタンクリックイベントのコードを以下に示します。用途がちょっとわかりません。配列を昇順でソートしようとしています。また、foreach を使用する必要があり、そこから何らかの方法でインデックスを取得する必要があります。試行 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,
4

2 に答える 2

0

クラスだけでなく、クラスに実装CompareToする必要があるようです。SortBankAccount

于 2013-02-21T00:34:48.700 に答える
0

まず、 a にforeachはインデックスがありません。インデックスが必要な場合は、for ループを使用します。
第二に、Sortクラスを実装する必要はありませんIComparable(これによりエラーが発生します)。比較ではなく、比較者です。必要に応じて実装IComparerするか、静的にすることができます。また、 QuickSort を実装し、確実に高速で優れているメソッドがある
のに、なぜバブル ソートの実装に飛び込むのでしょうArray.Sortか。List.Sort私はこれを避けました。

于 2013-02-21T00:51:29.830 に答える