gpt4 book ai didi

c# - 如何从合并排序中得到 O(n log(n))?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:54 26 4
gpt4 key购买 nike

如何知道我是否在链表上的合并排序实现中使用了 O(nlog(n))。我应该输入什么到 O(nlog(n)) 才能知道我在什么时候执行合并排序。

public static LinkedListNode<T> MergeSortLL<T>(LinkedListNode<T> Head) where T : IComparable<T>
{

if (Head?.Next == null)
{
return Head;
}
var middle = GetMiddle(Head);
var half = middle.Next;
middle.Next = null;

Head = Merge(MergeSortLL(Head), MergeSortLL(half));
return Head;
}

public static LinkedListNode<T> Merge<T>(LinkedListNode<T> Left, LinkedListNode<T> Right) where T : IComparable<T>
{

var mHead = new LinkedListNode<T>(default(T));
LinkedListNode<T> curr = mHead;

while (Left != null && Right != null)
{
if (Left.Value.CompareTo(Right.Value) <= 0)
{
curr.Next = Left;
Left = Left.Next;
}
else
{
curr.Next = Right;
Right = Right.Next;
}
curr = curr.Next;
}
curr.Next = (Left == null) ? Right : Left;

return mHead.Next;
}

public static LinkedListNode<T> GetMiddle<T>(LinkedListNode<T> Head) where T : IComparable<T>
{
if (Head == null)
{
return Head;
}

LinkedListNode<T> slow, fast;
slow = fast = Head;

while (fast.Next?.Next != null)
{
slow = slow.Next;
fast = fast.Next.Next;
}
return slow;
}

最佳答案

请注意,已知该算法执行 O(N*log(N)) 次比较。如果您想确认这一点(因为它已被证明),您可以放置​​一个计数器并在每次比较时递增它。

例如

public static int Comparisons;

public static LinkedListNode<T> Merge<T>(LinkedListNode<T> Left, LinkedListNode<T> Right) where T : IComparable<T>
{
// ...
Comparisons++;
if (Left.Value.CompareTo(Right.Value) <= 0)
// ...
}

检查它

LinkedListNode<int> head = ...;
Comparisons = 0;
head = MergeSortLL(head);
Debug.Print(Comparisons);

但请注意,众所周知,该算法具有显着的隐藏成本(即使使用慢速/快速指针技术也能找到中间点)。

关于c# - 如何从合并排序中得到 O(n log(n))?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406612/

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