Why is insertion into my tree faster on sorted input than random input?

前端 未结 8 1280
慢半拍i
慢半拍i 2021-02-02 12:33

Now I\'ve always heard binary search trees are faster to build from randomly selected data than ordered data, simply because ordered data requires explicit rebalancing to keep t

8条回答
  •  不要未来只要你来
    2021-02-02 12:43

    Yes it's the number of rotations that is causing the extra time. Here's what I did:

    • Remove the lines checking priority in HeapifyLeft and HeapifyRight so rotations are always done.
    • Added a Console.WriteLine after the if in RotateLeft and RotateRight.
    • Added a Console.WriteLine in the IsEmpty part of the Insert method to see what was being inserted.
    • Ran the test once with 5 values each.

    Output:

    TimeIt(5, RandomInsert)
    Inserting 0.593302943554382
    Inserting 0.348900582338171
    RotateRight
    Inserting 0.75496212381635
    RotateLeft
    RotateLeft
    Inserting 0.438848891499848
    RotateRight
    RotateLeft
    RotateRight
    Inserting 0.357057290783644
    RotateLeft
    RotateRight
    
    TimeIt(5, OrderedInsert)
    Inserting 0.150707998383189
    Inserting 1.58281302712057
    RotateLeft
    Inserting 2.23192588297274
    RotateLeft
    Inserting 3.30518679009061
    RotateLeft
    Inserting 4.32788012657682
    RotateLeft
    

    Result: 2 times as many rotations on random data.

提交回复
热议问题