4 ms·
> a sorting algorithm may take O(n log(n)) runtime which is pretty common but be able to operate on an array in-place, only requiring O(n) storage. If it's in-
by felixr 4y ago
> a sorting algorithm may take O(n log(n)) runtime which is pretty common but be able to operate on an array in-place, only requiring O(n) storage.
If it's in-place the sorting might only require constant space and it can be O(1 ) [edit: in terms of space complexity]
- unwind 4y agoDid you mean O(n)? It seems hard to sort n items without at least touching all of them once, which would make the time complexity linear (O(n)) instead of constant (O(1)). Or are you talking about storage needs? Then it sounds very hard to go sub-linear ... I'm confused. I'm certainly not a good theoretical computer scientist, but I did quickly google this and I couldn't find any trace of constant-time sorting (unless you goalpost it to have O(n log n) processors, but that is kind of cheating, here).
- Twisol 4y agoThe fiddly detail here is that big-O notation can be used to measure the usage of any resource, not just time. The poster above noted that an in-place sort might have constant space complexity -- although this only makes sense if you discount the space required for the input anyhow (which is literally linear in the input size!). Wikipedia distinguishes two measures of space, "total" (including the input) and "auxiliary" (excluding the input). The poster above you is likely referring to auxiliary space.
- felixr 4y agoSorry, wasn't clear. Was talking about the space complexity. If you sort in-place you don't need O(n) space, you can do with O(1 ). Not talking about time complexity
- aliceryhl 4y agoThey mean the amount of storage, and they're only counting additional memory allocated by the algorithm, and not the memory containing the input.
- sfink 4y agoWell... sorting a shuffled deck of cards can be done in O(1) time. def sort(self): pass def __getitem__(i): suit = int(i / 13) rank = i % 13 return f"{rank} of {('diamonds', 'hearts', 'spades', 'clubs')[suit]}"
- tempodox 4y agoO(1) would mean same storage requirement regardless of element count.
- felixr 4y agoYes. Simplest in-place example would be bubble sort. You might need a temp element for swaps, but that's it. Heap sort can also be done with constant space. You need of course O(n) space to store the original data; but that is not part of the sort algorithm.