algorithm - How to sort a 0/1 array with 2n/3 comparisons?

前端 未结 2 1177
感动是毒
感动是毒 2021-02-12 21:32

In Algorithm Design Manual, there is such an excise

4-26 Consider the problem of sorting a sequence of n 0’s and 1’s using comparisons. For each compari

相关标签:
2条回答
  • 2021-02-12 21:57

    "0 or 1 with equal probability" is the condition for "average" case. Other cases may have worse timing.

    Hint 1: 2/3 = 1/2 + 1/8 + 1/32 + 1/128 + ...

    Hint 2: Consider the sequence as a sequence of pairs and compare the items in each pair. Half will return equal; half will not. Of the half that are unequal you know which item in the pair is 0 and which is 1, so those need no more comparisons.

    0 讨论(0)
  • 2021-02-12 22:12

    No it means that at any position, you have the same chance (probability) of the input value being 0 or 1. this give you a first clue : your algorithm will be randomized.

    The runtime will depend on some random variable, and you need to take the expected value to obtain the average complexity case. Note that in this case, you have to detail during complexity analysis, as they require a precise constant (2/3n rather than simply O(n))

    Edit:
    Hint. In the sorted array (the one you get at the end), what is only thing which varies, knowing you have only 2 possible elements.

    0 讨论(0)
提交回复
热议问题