在地方排序为的IList&LT; T&GT;? [英] In place sort for IList<T>?
本文介绍了在地方排序为的IList&LT; T&GT;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
.NET是否有到位的排序功能的IList?我需要集合本身进行排序,而不是创建一个新的集合。
Does .NET have an in place sort function for IList? I need to sort the collection itself, not create a new collection.
编辑:我需要做的到位排序的原因是为了避免重绘UI除非有真正被改变。我不希望创建百年新的自定义控件,如果只有一个产品出来的地方。
The reason I need to do the sort in place is to avoid redrawing the UI unless something has actually changed. I don't want to create a hundred new custom controls if only one item is out of place.
推荐答案
如何就地快速排序 / InsertionSort /的希尔实现:
How about an in-place Quicksort / InsertionSort / ShellSort implementation:
public static class InPlaceQuickSort {
private static void Swap<T>(IList<T> set, int left, int right) {
T temp = set[left];
set[left] = set[right];
set[right] = temp;
}
private static Int32 Partition<T>(IList<T> set, int lBound, int rBound)
where T : IComparable<T> {
T pivot = set[rBound];
int left = lBound - 1;
int right = rBound;
while (true) {
while (set[++left].CompareTo(pivot) < 0) ;
while (set[--right].CompareTo(pivot) > 0) if (left == right) break;
if (left >= right) break;
Swap(set, left, right);
}
Swap(set, left, rBound);
return left;
}
private static IList<T> QuickSort<T>(IList<T> set, int lBound, int rBound)
where T : IComparable<T> {
if (lBound >= rBound) return set;
Int32 pivot = Partition(set, lBound, rBound);
QuickSort(set, lBound, pivot - 1);
QuickSort(set, pivot + 1, rBound);
return set;
}
public static IList<T> InsertionSort<T>(this IList<T> set)
where T : IComparable<T> {
for (Int32 index = 1; index < set.Count; index++) {
for (Int32 insertion = index; insertion > 0 && set[insertion - 1].CompareTo(set[insertion]) > 0; insertion--) {
Swap(set, insertion - 1, insertion);
}
}
return set;
}
public static IList<T> ShellSort<T>(this IList<T> set)
where T : IComparable<T> {
Int32 shell = 1;
while (shell < (set.Count / 3)) shell = shell * 3 + 1;
while (shell >= 1) {
for (Int32 index = shell; index < set.Count; index++) {
for (Int32 insertion = index; insertion >= shell && set[insertion - shell].CompareTo(set[insertion]) > 0; insertion -= shell) {
Swap(set, insertion - shell, insertion);
}
}
shell = shell / 3;
}
return set;
}
public static IList<T> QuickSort<T>(this IList<T> set)
where T : IComparable<T> {
return QuickSort<T>(set, 0, set.Count - 1);
}
}
和,这里是你如何使用它:
And, here's how you use it:
public static void Main() {
List<Int32> numbers = new List<int> { 1, 3, 2, 4, 2 };
foreach (Int32 number in numbers.QuickSort())
Console.WriteLine(number);
Console.ReadLine();
}
这篇关于在地方排序为的IList&LT; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文