In Java if I wanna sort any data independent to its data type I would use Comparable interface and I found out we have similar interface in C#, so I have simple sorting algorithm:
public static void Sort(IComparable[] arr)
{
bool swap = true;
while (swap)
{
swap = false;
for (int i = 0; i < arr.Length - 1; i++)
{
if (Less(arr[i + 1], arr[i]))
{
Exchange(arr, i, i + 1);
swap = true;
}
}
}
}
So I can sort any objects that implements IComparable
interface, but I can't sort any primitive datatypes and as I know C# doesn't have wrapper types for primitives like int -> Integer, but it has some structures like Int32 that actually implements IComparable interface but I still can't use it for some reason, for example:
static void Main(string[] args)
{
Int32[] ints = { 5, 2, 9, 0, 3};
BubbleSort.Sort(ints);
ReadKey();
}
I will get an error:
Error CS1503 Argument 1: cannot convert from 'int[]' to 'System.IComparable[]'
But if we check out metadata of Int32 we can see it implements IComparable
So,
- What I don't know?
- What's wrong here?
- How can I make it better to sort any data?