iamtonyzhou
iamtonyzhou

Reputation: 49

how to create a IComparable[] in c#?

public static void sort(IComparable[] a)
{
    int N = a.Length;
    for (int i = 0; i < N; i++)
    {
        for (int j = i; j > 0 && less(a[j], a[j - 1]); j--)
        {
           exch(a, j, j - 1);
        }
        isSorted(a, 0, i);
    }
    isSorted(a);
}

Above is simple sorting code I found in book, the code is wrote in java and I try to translate it in c#. Everything is fine, except how to pass the parameter. Int32 is implement the icamparable, but how can I create a instance of IComparable[] and pass to the sorting function.

IComparable[] b = new int[] { 2, 3, 3, 3, 3, 3, 3, 3 };

Does NOT work.

Upvotes: 0

Views: 107

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100575

If you want to initialize IComparable with array of int you need to create copy. The easiest to write code is to use LINQ's Cast and ToArray

 IComparable[] b = (new int[] { 2, 3, 3, 3, 3, 3, 3, 3 })
     .Cast<IComparable>().ToArray();

Note: normally you would use generics to write this the method - something like

 public static void Sort<T>(T[] a) where T: IComparable<T>

Upvotes: 5

Related Questions