我有一个列表,存储了一些整数。
我不喜欢默认的List.Sort()方法,因为我希望按实际整数大小对列表进行排序。
到目前为止,我有以下代码:
哦,这些整数是以字符串形式存储的,例如“1234”。这是我无法改变的。
哦,这些整数是以字符串形式存储的,例如“1234”。这是我无法改变的。
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;
}
}
}
}
据我所知,这是冒泡排序,对吗?我应该使用什么替代它呢?快速排序?而且,我可能需要帮助编写它。
哦,我的列表包含不到两千个元素,其中存储着字符串形式的数字。
另外,我这样调用我的 IComparer:
IntComparer intSort = New IntComparer();
List<T>.Sort(intSort);