AlgoTales · Roadmap

In-place vs out-of-place sorting

Beginner · 6 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

An in-place sort rearranges items inside the same array and needs almost no extra memory. An out-of-place sort builds a second list. The choice is about memory, safety of the original data, and sometimes speed.

Practical use cases

  • Web app: Sorting a large file on a small server. A cheap server with limited memory has to sort a big list of records. A method that works inside the same array fits comfortably, while one that needs a full second copy might run out of memory and crash the request.
  • Web app: Keeping the original order for undo. A spreadsheet-like page lets users sort a column and then press Undo. Sorting a copy, out of place, leaves the original data untouched, so Undo is simply switching back. The extra memory buys simplicity and safety.
  • System: Shared data in concurrent code. When several parts of a program read the same list, sorting it in place can surprise others in mid-read. Making a sorted copy avoids that kind of bug, which is why many frameworks return a new list instead of changing yours.

The story: The Extra Shelf

Kabir's school had a long row of lockers, and the sports teacher wanted the kit in them reversed before the match. Kabir had two options.

Option one: use only the lockers already there. He would grab the items from the first and last locker, swap them using his two hands, then move inward to the next pair. No extra lockers needed. The kit ended up reversed in the very same row, but the old arrangement was gone forever.

Option two: ask the school for a second empty row of lockers. He copied the items one by one from the old row into the new one, back to front. It cost a whole extra row of space, but the old row stayed exactly as it was, in case somebody needed it.

Programmers have names for these two styles. In-place algorithms work inside the original space, with only a tiny bit of extra memory. Out-of-place algorithms use extra memory proportional to the data. Neither is "better": it depends on whether memory is tight or the original must be kept.

How to spot this problem, and where you need it

You must decide whether to reorder the original list or make a sorted copy, balancing memory use against the risk of changing data that other code still needs.

Signs you need it

  • Memory is tight, the list is huge, or the server crashed with an out-of-memory error while sorting.
  • Other code, an undo feature or a cached copy still needs the original order after sorting.
  • You notice a bug where sorting a list in one place changed what another part of the page displays.

Where to use it in a project

  • Choosing between sort() that changes the array and a version that returns a new one, such as sort versus toSorted in JavaScript or sort versus sorted in Python.
  • Batch jobs on memory-limited servers, where an in-place method avoids doubling the memory.

The solution

Ask two questions. Do I still need the original order? If yes, sort a copy. Is memory scarce? If yes, sort in place, and accept that the original changes. Quick sort and heap sort work in place; classic merge sort needs a second array. Know which version your language function is, so you do not change a list by accident.

Payoff: Before: a crash when copying a 2 GB list or a surprise reorder elsewhere. After: the right choice, so memory stays safe and original data stays intact.

Explain it like I am 8

You want to flip your row of toy cars around. You can swap the cars in their own parking row, which is in-place and uses no new space. Or you can park them in a second row in reverse order, which is out-of-place and needs lots of space but keeps the first row safe.

How it works, step by step

  1. Ask: how much extra memory does the algorithm need besides the input?
  2. In-place: only a constant bit (a few variables), such as a temp variable for swapping.
  3. Out-of-place: extra memory that grows with the input, like a whole second array.
  4. In-place usually changes the original. Out-of-place can leave it untouched.
  5. Examples: insertion, selection, heap and quick sort are in-place (quick uses a small stack). Merge sort and counting sort are out-of-place.

The code in four languages

PHP

<?php
// In place: sorts the SAME array (passed by reference), only a few extra variables.
function insertionSortInPlace(array &$a): void {
    for ($i = 1; $i < count($a); $i++) {
        $key = $a[$i];
        $j = $i - 1;
        while ($j >= 0 && $a[$j] > $key) { $a[$j + 1] = $a[$j]; $j--; }
        $a[$j + 1] = $key;
    }
}
// Out of place: builds NEW arrays and leaves the input alone.
function mergeSorted(array $a): array {
    if (count($a) <= 1) return $a;
    $mid = intdiv(count($a), 2);
    $l = mergeSorted(array_slice($a, 0, $mid));
    $r = mergeSorted(array_slice($a, $mid));
    $out = [];
    while ($l && $r) $out[] = $l[0] <= $r[0] ? array_shift($l) : array_shift($r);
    return array_merge($out, $l, $r);
}
$marks = [5, 2, 9, 1];
$copy = mergeSorted($marks);
echo 'After out-of-place: original=', implode(',', $marks), ' new=', implode(',', $copy), "\n";
insertionSortInPlace($marks);
echo 'After in-place:     original=', implode(',', $marks), "\n";

JavaScript

// In place: sorts the SAME array, only a few extra variables.
function insertionSortInPlace(a) {
  for (let i = 1; i < a.length; i++) {
    const key = a[i];
    let j = i - 1;
    while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
    a[j + 1] = key;
  }
}
// Out of place: builds NEW arrays and leaves the input alone.
function mergeSorted(a) {
  if (a.length <= 1) return a;
  const mid = Math.floor(a.length / 2);
  const l = mergeSorted(a.slice(0, mid));
  const r = mergeSorted(a.slice(mid));
  const out = [];
  while (l.length && r.length) out.push(l[0] <= r[0] ? l.shift() : r.shift());
  return out.concat(l, r);
}
const marks = [5, 2, 9, 1];
const copy = mergeSorted(marks);
console.log('After out-of-place: original=' + marks.join(',') + ' new=' + copy.join(','));
insertionSortInPlace(marks);
console.log('After in-place:     original=' + marks.join(','));

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    // In place: sorts the SAME array, only a few extra variables.
    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;
        }
    }

    // Out of place: builds NEW arrays and leaves the input alone.
    static int[] mergeSorted(int[] a) {
        if (a.length <= 1) return a;
        int mid = a.length / 2;
        int[] l = mergeSorted(Arrays.copyOfRange(a, 0, mid));
        int[] r = mergeSorted(Arrays.copyOfRange(a, mid, a.length));
        int[] out = new int[a.length];
        int i = 0, j = 0, k = 0;
        while (i < l.length && j < r.length) out[k++] = l[i] <= r[j] ? l[i++] : r[j++];
        while (i < l.length) out[k++] = l[i++];
        while (j < r.length) out[k++] = r[j++];
        return out;
    }

    static String join(int[] a) {
        return Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(","));
    }

    public static void main(String[] args) {
        int[] marks = {5, 2, 9, 1};
        int[] copy = mergeSorted(marks);           // marks is untouched, copy is a new array
        System.out.println("After out-of-place: original=" + join(marks) + " new=" + join(copy));
        insertionSortInPlace(marks);               // now marks itself is rearranged
        System.out.println("After in-place:     original=" + join(marks));
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// In place: sorts the SAME slice, only a few extra variables.
func insertionSortInPlace(a []int) {
	for i := 1; i < len(a); i++ {
		key := a[i]
		j := i - 1
		for j >= 0 && a[j] > key {
			a[j+1] = a[j]
			j--
		}
		a[j+1] = key
	}
}

// Out of place: builds NEW slices and leaves the input alone.
func mergeSorted(a []int) []int {
	if len(a) <= 1 {
		return a
	}
	mid := len(a) / 2
	l := mergeSorted(a[:mid])
	r := mergeSorted(a[mid:])
	out := make([]int, 0, len(a))
	i, j := 0, 0
	for i < len(l) && j < len(r) {
		if l[i] <= r[j] {
			out = append(out, l[i])
			i++
		} else {
			out = append(out, r[j])
			j++
		}
	}
	out = append(out, l[i:]...)
	return append(out, r[j:]...)
}

func join(a []int) string {
	parts := make([]string, len(a))
	for i, v := range a {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, ",")
}

func main() {
	marks := []int{5, 2, 9, 1}
	copyOfMarks := mergeSorted(marks) // marks is untouched, copyOfMarks is a new slice
	fmt.Println("After out-of-place: original=" + join(marks) + " new=" + join(copyOfMarks))
	insertionSortInPlace(marks) // now marks itself is rearranged
	fmt.Println("After in-place:     original=" + join(marks))
}

Time: Depends on the algorithm · Extra space: In-place: O(1) extra. Out-of-place: O(n) extra. This property is only about extra memory. Quick sort is counted in-place even though its recursion uses a small O(log n) stack.

Watch out for

  • Thinking in-place means "no extra memory at all". A few variables, and often a small recursion stack, are still allowed.
  • Calling an in-place sort and expecting the original to survive. It has been overwritten.
  • Forgetting that in PHP an array is copied on pass-by-value, so an "in-place" PHP function needs &$a.

Quick check

  1. Which describes an in-place sort?
    • It needs only a tiny, fixed amount of extra memory
    • It always keeps the original untouched
    • It must use recursion
  2. Which sort typically needs an extra array of size n to merge into?
    • Merge sort
    • Selection sort
    • Heap sort
  3. Why might you choose an out-of-place sort?
    • It uses less memory
    • It is always faster
    • The original data must stay unchanged