I have a list which stores a lost of integers. I don't like the default List.Sort() works, as I want the list to be ordered by size of the actual int. So far I have this:
Oh, and the ints are stored in strings, e.g "1234". It is something I can not change.
public class IntComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null)
{
if (y == null)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == null)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int xInt = Convert.ToInt32(x);
int yInt = Convert.ToInt32(y);
if (x > y)
{
// If the strings are not of equal length,
// the longer string is greater.
//
return 1;
}
else if (xInt == yInt)
{
return 0;
}
else
{
// If the strings are of equal length,
// sort them with ordinary string comparison.
//
return -1;
}
}
}
}
But to my knowledge, this is bubble-sort, correct? What should I implement instead? Quicksort? also, I might need help writing it.
Oh and my list contains short of 2 thousand elements which stores numbers in strings
Also, I call my IComparer like this:
IntComparer intSort = New IntComparer();
List<T>.Sort(intSort);
Assuming you want to sort by the value of the integer stored as a string, you can simply do something like this:
numbers.Sort((x,y) => Int32.Parse(x).CompareTo(Int32.Parse(y)));
You should be aware that the comparer and the sort algorithm do not determine each other. So this comparer can be used with bubble-sort as well as with quicksort, heapsort or any other sort algorithm. The built-in sort algorithm of List.Sort is quicksort, according to MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With