How can a sorting algorithm have a space complexity of O(1)?

The space complexity is actually the additional space complexity used by your algorithm, i.e. the extra space that you need, apart from the initial space occupied by the data. Bubble-sort and insertion sort use only a constant additional space, apart from the original data, so they are O(1) in space complexity.


A sorting algorithm has space complexity O(1) by allocating a constant amount of space, such as a few variables for iteration and such, that are not proportional to the size of the input.

An example of sorting algorithm that is not O(1) in terms of space would be most implementations of mergesort, which allocate an auxiliary array, making it O(n). Quicksort might look like O(1) in theory, but the call stack counts like space and therefore it is said to be O(log n).

Examples of sorting algorithms with O(1) space complexity include: selection sort, insertion sort, shell sort and heapsort.