I have tried to use IComparable and researched but I cannot figure out why this will not work. I want to compare strings and ints but I don't understand how to use the ICompareable interface to do compareTo on a type of Generic.
How do I implement the CompareTo to handle Generics?
public class QuickSort : IComparable
{
public static int Partition<T>(ref T[] arr, int lo, int hi)
{
int i = lo + 1;
int j = hi;
while (j > i)
{
while (arr[i].) // <- Cannot apply CompareTo
i++;
while (arr[j] > arr[lo])
j--;
Swap(ref arr[i], ref arr[j]);
}
Swap(ref arr[lo], ref arr[j]);
return j;
}
}
You have to specify that T
can be compared, the compiler can't know otherwise that type to expect. This way you can use CompareTo
for both your conditions:
public class QuickSort
{
public static int Partition<T>(T[] arr, int lo, int hi) where T : IComparable
{
int i = lo + 1;
int j = hi;
while (j > i)
{
while (arr[i].CompareTo(arr[lo]) == 0)
i++;
while (arr[j].CompareTo(arr[lo]) > 0) // means arr[j] > arr[lo]
j--;
Swap(ref arr[i], ref arr[j]);
}
Swap(ref arr[lo], ref arr[j]);
return j;
}
}
Also, I don't think you want to compare different QuickSort
instances, so I removed its interface.
Update: Based on Hawkmooon's comment, I took a second look at your method and thought its signature can be even simpler:
public static int Partition(IComparable[] arr, int lo, int hi)
{
int i = lo + 1;
int j = hi;
while (j > i)
{
while (arr[i].CompareTo(arr[lo]) == 0)
i++;
while (arr[j].CompareTo(arr[lo]) > 0)
j--;
Swap(ref arr[i], ref arr[j]);
}
Swap(ref arr[lo], ref arr[j]);
return j;
}
I think your code may be missing something. Just in case, here you have a full C# example of a working quicksort method.