我有一个存储丢失的整数的列表。 我不喜欢默认的 List.Sort() 工作,因为我希望列表按实际 int 的大小排序。 到目前为止我有这个:
哦,整数存储在字符串中,例如“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;
}
}
}
}
但据我所知,这是冒泡排序,对吗? 我应该实现什么?快排?另外,我可能需要帮助来编写它。
哦,我的列表包含不到 2000 个元素,这些元素将数字存储在字符串中
另外,我这样称呼我的 IComparer:
IntComparer intSort = New IntComparer();
List<T>.Sort(intSort);
最佳答案
假设你想按存储为字符串的整数的值排序,你可以简单地做这样的事情:
numbers.Sort((x,y) => Int32.Parse(x).CompareTo(Int32.Parse(y)));
关于c# - 优化 list<T>.Sort(Comparer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/771779/