Binary vs Linear searches for unsorted N elements

前端 未结 5 915
予麋鹿
予麋鹿 2021-01-19 00:44

I try to understand a formula when we should use quicksort. For instance, we have an array with N = 1_000_000 elements. If we will search only once, we sho

5条回答
  •  情深已故
    2021-01-19 00:53

    Assuming n elements and m searches, with crude approximations

    • the cost of the sort will be C0.n.log n,

    • the cost of the m binary searches C1.m.log n,

    • the cost of the m linear searches C2.m.n,

    with C2 ~ C1 < C0.

    Now you compare

    C0.n.log n + C1.m.log n vs. C2.m.n
    

    or

    C0.n.log n / (C2.n - C1.log n)  vs. m
    

    For reasonably large n, the breakeven point is about C0.log n / C2.

    For instance, taking C0 / C2 = 5, n = 1000000 gives m = 100.

提交回复
热议问题