Since k seems to be fairly small, insertion sorting is probably the most obvious and generally accepted algorithm.
In sorting inserts on random elements, you have to scan through N elements, and you need to move each of them on average at N / 2 positions, which gives the general N * N / 2 operations. The constant "/ 2" is ignored in the large-O (or similar) characteristic, which gives the complexity of O (N 2 ).
In the case where you offer, the expected number of operations is ~ N * K / 2, but since k is a constant, the entire term k/2 ignored in the characteristic of large O, so the overall complexity is O (N).
Jerry Coffin Apr 28 '10 at 4:36
source share