gpt4 book ai didi

.net - 是否在适当位置为IList 排序?

转载 作者:行者123 更新时间:2023-12-02 08:38:11 25 4
gpt4 key购买 nike

.NET是否具有针对IList的就地排序功能?我需要对集​​合本身进行排序,而不是创建新集合。

编辑:我需要进行适当排序的原因是避免重新绘制UI,除非实际更改过。如果只有一项不合适,我不想创建一百个新的自定义控件。

编辑:同样,这是关于就地排序的问题,而不仅仅是一般的排序。

最佳答案

就地Quicksort / InsertionSort / ShellSort实现如何:

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);
}
}

并且,这是您的用法:
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();
}

关于.net - 是否在适当位置为IList <T>排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19167193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com