In-Place Algorithm

An in-place algorithm transforms its input while using only a small, constant amount of extra memory beyond the input itself, usually described as O(1) auxiliary space. Rather than building a separate copy of the data, it rearranges the original in place, overwriting elements as it goes. This is the opposite of an algorithm that allocates a second array or other structure proportional in size to the input.

Sorting provides the standard examples. Heapsort rearranges an array into a heap and then repeatedly extracts the largest element into the tail of the same array, sorting without any auxiliary array. Quicksort partitions a range around a pivot by swapping elements within the array and recursing on the parts, so its core work is in place. By contrast, the straightforward version of merge sort needs extra space to hold the merged output, which is why it is not naturally in place. MIT’s 6.006 Introduction to Algorithms treats these sorting methods and the data structures behind them, including heaps and arrays, as core material.

A simple non-sorting example is reversing an array by swapping the first and last elements, then the second and second-to-last, working inward until the pointers meet. The reversal happens entirely within the original array using just a couple of index variables.

In-place algorithms are valuable when memory is scarce or when copying large inputs would be costly, since they save space at the level of a space-time tradeoff. The cost is often in clarity: in-place code tends to involve careful index manipulation and destroys the original input, so it can be harder to read and to reason about than a version that returns a fresh result.