AlgoTales · Roadmap

Stable vs unstable sorting

Intermediate · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A stable sort keeps items that tie in their original order, while an unstable sort may shuffle them. This matters whenever you sort the same list by two things in turn, such as by city and then by name.

Practical use cases

  • Web app: Sorting a product list twice. A shop list is first sorted by name, and then the shopper clicks "Sort by price". With a stable sort, products with the same price stay in alphabetical order. With an unstable one they jump around, and the page looks random and broken.
  • Web app: Admin table with clickable headers. An admin user table lets staff click the "Department" header after sorting by "Joined date". A stable sort keeps people in each department ordered by date. Staff expect this, and an unstable sort makes them think the table is buggy.
  • System: Radix sort depends on stability. Radix sort depends on stability to work at all, since each digit pass must keep the order from the earlier pass. Without it the final order would be wrong. So stability is not only about tidy tables: in some algorithms it is a correctness requirement.

The story: The Report Card Tie

When the exam results came out, Aarav and Mira both scored 8. On the printed list, Aarav came first, because the class list is alphabetical. Everybody was happy.

Then Mrs. Sharma re-sorted the list by marks, and now Mira appeared above Aarav. "That is not fair", said Aarav, "we have the same marks and the list was in my favour before!" The teacher laughed and explained that the sorting method she used did not care about ties: it was free to shuffle equal items.

"There are two kinds of sorting methods", she said. "A stable sort promises that equal items stay in the same relative order as before. An unstable sort makes no such promise." For plain numbers it makes no difference, but for records, like students with names, it matters a lot.

Stability is what lets you sort in layers: sort by name, then stably by marks, and you get "marks, and by name within equal marks". Bubble, insertion and merge sort are stable. Selection, quick and heap sort are not, unless you add extra care.

How to spot this problem, and where you need it

Items with equal sort values are changing places in a confusing way, so a list sorted first by one column and then another no longer looks right.

Signs you need it

  • Rows with the same value, such as the same price or score, appear in a different order every time you re-sort or refresh.
  • You sort by one column and then another and expect the first order to remain within ties, but it does not.
  • The problem statement says "keep the original relative order" or "sort by multiple keys".

Where to use it in a project

  • Sortable table headers in admin panels and listing pages where users click different columns.
  • Pipelines that sort in several passes, such as radix sort, or reports sorted by department then name.

The solution

Choose a stable sort when ties matter. Merge sort and insertion sort are stable by nature; quick sort and heap sort are not. If you only have an unstable sort, add the original position as a final tie-breaker in your comparison. Then sort by the least important column first and the most important column last, and the earlier orders survive inside ties.

Payoff: Before: same-price products shuffled at every click. After: ties stay in alphabetical order, so the table looks calm and predictable.

Explain it like I am 8

Two friends with the same height stand in a line, one behind the other. A stable sort keeps the first friend in front, always. An unstable sort might switch them, because it only cares about height, not who was first.

How it works, step by step

  1. Tie: two items have the same sort key (for example, the same marks).
  2. A stable sort keeps tied items in the same order they had in the input.
  3. An unstable sort may reorder tied items, because it moves items by long-distance swaps.
  4. Stability matters when items are records sorted in layers (name, then marks), not for plain numbers.
  5. Stable: bubble, insertion, merge, counting, radix. Usually unstable: selection, quick, heap.

The code in four languages

PHP

<?php
// Each record is [name, marks]. Sort by marks and watch what happens to ties.
function insertionSortByMarks(array $r): array {       // STABLE: only moves past strictly bigger
    for ($i = 1; $i < count($r); $i++) {
        $key = $r[$i];
        $j = $i - 1;
        while ($j >= 0 && $r[$j][1] > $key[1]) { $r[$j + 1] = $r[$j]; $j--; }
        $r[$j + 1] = $key;
    }
    return $r;
}
function selectionSortByMarks(array $r): array {       // UNSTABLE: long-distance swaps
    for ($i = 0; $i < count($r) - 1; $i++) {
        $min = $i;
        for ($j = $i + 1; $j < count($r); $j++) {
            if ($r[$j][1] < $r[$min][1]) $min = $j;
        }
        [$r[$i], $r[$min]] = [$r[$min], $r[$i]];
    }
    return $r;
}
function names(array $r): string { return implode(', ', array_column($r, 0)); }

$class = [['Aarav', 8], ['Zoya', 7], ['Mira', 8], ['Kabir', 7], ['Raju', 6]];
echo 'Stable:   ', names(insertionSortByMarks($class)), "\n";   // Raju, Zoya, Kabir, Aarav, Mira
echo 'Unstable: ', names(selectionSortByMarks($class)), "\n";   // Raju, Zoya, Kabir, Mira, Aarav

JavaScript

// Each record is [name, marks]. Sort by marks and watch what happens to ties.
function insertionSortByMarks(input) {          // STABLE: only moves past strictly bigger
  const r = [...input];
  for (let i = 1; i < r.length; i++) {
    const key = r[i];
    let j = i - 1;
    while (j >= 0 && r[j][1] > key[1]) { r[j + 1] = r[j]; j--; }
    r[j + 1] = key;
  }
  return r;
}
function selectionSortByMarks(input) {          // UNSTABLE: long-distance swaps
  const r = [...input];
  for (let i = 0; i < r.length - 1; i++) {
    let min = i;
    for (let j = i + 1; j < r.length; j++) {
      if (r[j][1] < r[min][1]) min = j;
    }
    [r[i], r[min]] = [r[min], r[i]];
  }
  return r;
}
const names = (r) => r.map(x => x[0]).join(', ');

const cls = [['Aarav', 8], ['Zoya', 7], ['Mira', 8], ['Kabir', 7], ['Raju', 6]];
console.log('Stable:   ' + names(insertionSortByMarks(cls)));   // Raju, Zoya, Kabir, Aarav, Mira
console.log('Unstable: ' + names(selectionSortByMarks(cls)));   // Raju, Zoya, Kabir, Mira, Aarav

Java

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

public class Main {
    // Each record is a student with marks. Sort by marks and watch what happens to ties.
    record Student(String name, int marks) {}

    // STABLE: only moves past strictly bigger
    static Student[] insertionSortByMarks(Student[] input) {
        Student[] r = input.clone();
        for (int i = 1; i < r.length; i++) {
            Student key = r[i];
            int j = i - 1;
            while (j >= 0 && r[j].marks() > key.marks()) { r[j + 1] = r[j]; j--; }
            r[j + 1] = key;
        }
        return r;
    }

    // UNSTABLE: long-distance swaps
    static Student[] selectionSortByMarks(Student[] input) {
        Student[] r = input.clone();
        for (int i = 0; i < r.length - 1; i++) {
            int min = i;
            for (int j = i + 1; j < r.length; j++) {
                if (r[j].marks() < r[min].marks()) min = j;
            }
            Student tmp = r[i]; r[i] = r[min]; r[min] = tmp;
        }
        return r;
    }

    static String names(Student[] r) {
        return Arrays.stream(r).map(Student::name).collect(Collectors.joining(", "));
    }

    public static void main(String[] args) {
        Student[] cls = {
            new Student("Aarav", 8), new Student("Zoya", 7), new Student("Mira", 8),
            new Student("Kabir", 7), new Student("Raju", 6)
        };
        System.out.println("Stable:   " + names(insertionSortByMarks(cls)));   // Raju, Zoya, Kabir, Aarav, Mira
        System.out.println("Unstable: " + names(selectionSortByMarks(cls)));   // Raju, Zoya, Kabir, Mira, Aarav
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// Each record is a student with marks. Sort by marks and watch what happens to ties.
type Student struct {
	name  string
	marks int
}

// insertionSortByMarks is STABLE: it only moves past strictly bigger marks.
func insertionSortByMarks(input []Student) []Student {
	r := append([]Student(nil), input...)
	for i := 1; i < len(r); i++ {
		key := r[i]
		j := i - 1
		for j >= 0 && r[j].marks > key.marks {
			r[j+1] = r[j]
			j--
		}
		r[j+1] = key
	}
	return r
}

// selectionSortByMarks is UNSTABLE: long-distance swaps.
func selectionSortByMarks(input []Student) []Student {
	r := append([]Student(nil), input...)
	for i := 0; i < len(r)-1; i++ {
		min := i
		for j := i + 1; j < len(r); j++ {
			if r[j].marks < r[min].marks {
				min = j
			}
		}
		r[i], r[min] = r[min], r[i]
	}
	return r
}

func names(r []Student) string {
	parts := make([]string, len(r))
	for i, s := range r {
		parts[i] = s.name
	}
	return strings.Join(parts, ", ")
}

func main() {
	class := []Student{{"Aarav", 8}, {"Zoya", 7}, {"Mira", 8}, {"Kabir", 7}, {"Raju", 6}}
	fmt.Println("Stable:   " + names(insertionSortByMarks(class))) // Raju, Zoya, Kabir, Aarav, Mira
	fmt.Println("Unstable: " + names(selectionSortByMarks(class))) // Raju, Zoya, Kabir, Mira, Aarav
}

Time: Stable sorts: O(n²) simple, O(n log n) merge · Extra space: Varies by algorithm. Stability is a property, not a speed. Making an unstable sort stable usually costs extra memory or time.

Watch out for

  • Assuming every library sort is stable. JavaScript and PHP 8 sorts are, but C's qsort is not guaranteed to be.
  • Not noticing instability because the test data had no ties. Always test with equal keys.
  • Using >= instead of > in insertion sort, which quietly makes it unstable.

Quick check

  1. What does a stable sort guarantee?
    • Equal items keep their original relative order
    • It is faster than other sorts
    • It never uses extra memory
  2. Which of these is typically unstable?
    • Merge sort
    • Insertion sort
    • Selection sort
  3. When does stability really matter?
    • Sorting plain numbers
    • Sorting records by one field after another
    • Sorting an empty list