Lesson 2 · Core algorithms

In-Place vs Out-of-Place Sorting

An in-place sort rearranges the input inside its own memory, using only a few extra variables (and at most a logarithmic stack). An out-of-place sort writes its result somewhere else and needs memory in proportion to the input. Neither is better in general; the trade is memory against keeping the original and, often, stability.

In-Place vs Out-of-Place Sorting concept diagramFour sorts on the same eight-value input, with extra memory drawn to scale beside the input. Heap sort needs one temporary cell. Quicksort needs about three stack frames. Merge sort needs a buffer as long as the input. Counting sort needs a table of ten counts and an output array of eight. The first two are in place; the last two are out of place.same 8 values · extra memory to scaleinput (not counted)auxiliary spaceheap sortin placetemp1 temp cell · O(1)quicksortin placestack~log₂ 8 = 3 stack frames · O(log n)merge sortout of placebufferbuffer of 8 · O(n)counting sortout of placecountsoutput10 counts + 8 output · O(n + k)
1

What In Place Means

An in-place sorting algorithm rearranges the values inside the array it was given. Besides that array it uses only a fixed number of variables: an index or two, and one temporary value for a swap. That extra memory is called auxiliary space, and for an in-place sort it is O(1). Quicksort is also counted as in place, although its recursion stack takes O(log n) on average.

An out-of-place sorting method writes the sorted result into new memory: a second array, a set of buckets, or a count table. Its auxiliary space grows with the input, O(n) or more. The input itself may be left untouched.

  • Count the memory beyond the input, not the input itself
  • O(1) or O(log n) auxiliary space: in place
  • O(n) auxiliary space or more: out of place
2

How Each Sort Uses Memory

Insertion, selection, bubble, shell and heap sort move values by swapping or shifting inside the array, so they are in place with O(1) extra. Quicksort partitions in place, but each recursive call keeps a frame on the stack: about log₂ n frames on balanced splits, and up to n on bad ones unless the code always recurses into the smaller side first.

Merge sort combines two sorted halves by repeatedly taking the smaller front value, and the result needs somewhere to go, so it uses an O(n) buffer. Counting sort needs a count for each possible key and an output array, O(n + k). Radix sort runs a counting pass per digit and needs the same output array.

Auxiliary space of common sorts
SortExtra memoryIn place?Stable?
Insertion, bubbleO(1)YesYes
Selection, shell, heapO(1)YesNo
QuicksortO(log n) stackYesNo
Merge sortO(n) bufferNoYes
Counting sortO(n + k)NoYes
Radix sort (LSD)O(n + base)NoYes
  • Swapping and shifting stay inside the array
  • Merging and distributing need somewhere else to write
3

Why Merging Needs a Buffer

Merge the sorted halves 3, 6, 8 and 1, 2, 5 inside one array. The smallest value, 1, belongs in slot 0, but slot 0 holds 3, which has not been placed yet. Writing 1 there destroys 3 unless it is moved first, and moving it shifts everything after it. A separate buffer avoids the problem: write 1, 2, 3, 5, 6, 8 into fresh memory, then copy back or return the buffer.

In-place merging does exist, but it is either O(n log² n) or so complicated that it is slower in practice. This is the root of a common trade-off: a sort that is fast in the worst case, stable and in place all at once is rare. Heap sort gives up stability; merge sort gives up memory. Sorting algorithms compares stability across every sort.

  • The merge's write position catches up with values not yet read
  • Merge sort: O(n log n) worst case and stable, but O(n) extra
  • Heap sort: O(n log n) worst case and O(1) extra, but unstable
Key reference

Terms, operations, and practical uses

Key terms

  • Auxiliary spaceMemory a sort uses beyond the input itself.
  • In placeO(1) extra memory, or O(log n) with a recursion stack.
  • Out of placeWrites the result to new memory that grows with n.
Implementation

Code in Python, C++ and Java

def insertion_sort_in_place(a):
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key


def merge_sort_copy(a):
    if len(a) <= 1:
        return a[:]
    mid = len(a) // 2
    left, right = merge_sort_copy(a[:mid]), merge_sort_copy(a[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i])
            i += 1
        else:
            out.append(right[j])
            j += 1
    return out + left[i:] + right[j:]


data = [6, 3, 8, 1, 5, 2]
copy = merge_sort_copy(data)
print("out of place:", copy, "original:", data)

alias = data
insertion_sort_in_place(data)
print("in place:", data, "alias sees:", alias)

print("list.sort() returns", [3, 1, 2].sort())
print("sorted() returns", sorted([3, 1, 2]))
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

void insertionSortInPlace(vector<int>& a) {
    for (size_t i = 1; i < a.size(); i++) {
        int key = a[i];
        int j = (int)i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

vector<int> mergeSortCopy(const vector<int>& a) {
    if (a.size() <= 1) return a;
    size_t mid = a.size() / 2;
    vector<int> left = mergeSortCopy(vector<int>(a.begin(), a.begin() + mid));
    vector<int> right = mergeSortCopy(vector<int>(a.begin() + mid, a.end()));
    vector<int> out;
    size_t i = 0, j = 0;
    while (i < left.size() && j < right.size()) out.push_back(left[i] <= right[j] ? left[i++] : right[j++]);
    while (i < left.size()) out.push_back(left[i++]);
    while (j < right.size()) out.push_back(right[j++]);
    return out;
}

string show(const vector<int>& v) {
    string s = "[";
    for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
    return s + "]";
}

int main() {
    vector<int> data = {6, 3, 8, 1, 5, 2};
    vector<int> copy = mergeSortCopy(data);
    cout << "out of place: " << show(copy) << " original: " << show(data) << "\n";

    vector<int>& alias = data;
    insertionSortInPlace(data);
    cout << "in place: " << show(data) << " alias sees: " << show(alias) << "\n";

    vector<int> v = {3, 1, 2};
    sort(v.begin(), v.end());
    cout << "std::sort sorts in place: " << show(v) << "\n";
}
import java.util.Arrays;

public class Main {
    static void insertionSortInPlace(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int key = a[i];
            int j = i - 1;
            while (j >= 0 && a[j] > key) {
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = key;
        }
    }

    static int[] mergeSortCopy(int[] a) {
        if (a.length <= 1) return a.clone();
        int mid = a.length / 2;
        int[] left = mergeSortCopy(Arrays.copyOfRange(a, 0, mid));
        int[] right = mergeSortCopy(Arrays.copyOfRange(a, mid, a.length));
        int[] out = new int[a.length];
        int i = 0, j = 0, k = 0;
        while (i < left.length && j < right.length) out[k++] = left[i] <= right[j] ? left[i++] : right[j++];
        while (i < left.length) out[k++] = left[i++];
        while (j < right.length) out[k++] = right[j++];
        return out;
    }

    public static void main(String[] args) {
        int[] data = {6, 3, 8, 1, 5, 2};
        int[] copy = mergeSortCopy(data);
        System.out.println("out of place: " + Arrays.toString(copy) + " original: " + Arrays.toString(data));

        int[] alias = data;
        insertionSortInPlace(data);
        System.out.println("in place: " + Arrays.toString(data) + " alias sees: " + Arrays.toString(alias));

        int[] v = {3, 1, 2};
        Arrays.sort(v);
        System.out.println("Arrays.sort sorts in place: " + Arrays.toString(v));
    }
}
Watch it run

Step through it

Running on [6, 3, 8, 1, 5, 2]

input [6, 3, 8, 1, 5, 2]extra cells: 0array603182135425in place: rearrange these slots · out of place: write a new arrayauxiliary space = memory beyond the input
Step 1

One array, six values

Both kinds of sort start from the same six values. The question is not how fast they finish but where the sorted result is written: back into these six slots, or into new memory. That extra memory is the auxiliary space.

Output
1 / 11
4

In Place vs Out of Place Sorting in Practice

The choice between in-place and out-of-place sorting usually comes from what the caller needs. Sorting in place saves memory, which matters for huge arrays or small devices, and it is cache-friendly because nothing is copied. Sorting out of place keeps the original order, which matters when other code still reads it, when data must not change (an immutable tuple or a shared input), or when parallel threads each read the same input.

Library names follow the same split. In Python, list.sort() changes the list and returns None, while sorted(x) returns a new list and leaves x alone. C++ std::sort and Java Arrays.sort sort the array you pass. Java has no copying sort for arrays, so code that needs the original first makes a copy with clone().

"In place" in an API means the result replaces your data; it does not promise O(1) memory. Python's and Java's object sorts use Timsort, which merges runs through a temporary buffer of up to n/2 values. C++ std::stable_sort also takes a buffer when it can get one.

  • Need the original afterwards: sort a copy
  • Tight memory or a huge array: in place
  • b = a.sort() in Python sets b to None, a classic bug
5

Edge Cases

Two names for one array is the trap of in-place sorting. If view = data and you sort data in place, view changes too, because there is only one array. Sort a copy whenever another part of the program holds a reference and expects the old order.

Recursion counts. A quicksort that always picks the last element as pivot recurses n deep on already sorted input, so its "in place" sort uses O(n) stack and may overflow it. Recursing on the smaller part and looping on the larger keeps the stack at O(log n) whatever the input.

  • Aliases see every in-place change
  • Worst-case quicksort stack is O(n) without the smaller-side rule
  • Linked lists merge in place: relinking nodes needs no buffer