Can you sort n integers in O(n) amortized complexity?

前端 未结 4 2166
星月不相逢
星月不相逢 2021-01-05 01:38

Is it theoretically possible to sort an array of n integers in an amortized complexity of O(n)?

What about trying to create a worst case of O(n) complexity?

4条回答
  •  走了就别回头了
    2021-01-05 01:58

    If the integers are in a limited range then an O(n) "sort" of them would involve having a bit vector of "n" bits ... looping over the integers in question and setting the n%8 bit of offset n//8 in that byte array to true. That is an "O(n)" operation. Another loop over that bit array to list/enumerate/return/print all the set bits is, likewise, an O(n) operation. (Naturally O(2n) is reduced to O(n)).

    This is a special case where n is small enough to fit within memory or in a file (with seek()) operations). It is not a general solution; but it is described in Bentley's "Programming Pearls" --- and was allegedly a practical solution to a real-world problem (involving something like a "freelist" of telephone numbers ... something like: find the first available phone number that could be issued to a new subscriber).

    (Note: log(10*10) is ~24 bits to represent every possible integer up to 10 digits in length ... so there's plenty of room in 2*31 bits of a typical Unix/Linux maximum sized memory mapping).

提交回复
热议问题