Coding Patterns/Basics · B1

Sorting is a constraint decision.

Learn the mechanics

Bubble, insertion, selection

Use explicit passes to see how local swaps, a growing prefix, and suffix minima establish order.

Scale comparisons

Merge and quick sort

Choose predictable stable merging or in-place partitioning when quadratic passes stop fitting the input size.

Exploit structure

Count or partition

Use bounded key ranges or a small set of values to achieve linear work without general comparison sorting.

Runnable session

Sort with a reason.

7 exercises · 49 named checks · Python 3 in your browser · saved locally

Easy16 min target

Bubble Sort Passes

Implement bubble_sort(values). Return a new ascending list without mutating values. Use adjacent swaps and stop early when a complete pass makes no swaps; do not use sorted() or list.sort().

Examples

Input [7, 3, 5, 2]
Output [2, 3, 5, 7]

Each pass bubbles the largest remaining value to the end of the unsorted region.

Input [1, 2, 3, 4]
Output [1, 2, 3, 4]

An already-sorted input finishes after one swap-free pass.

Constraints

  • 0 ≤ len(values) ≤ 2,000
  • Values are integers
  • The input list must remain unchanged
  • Stop after a pass with no swaps
Python 3
ChecksRun when you’re ready

Your code runs privately in the browser. Visible checks cover empty, boundary, and representative cases.

Basics coverage

Six algorithms. Six different invariants.

Watch the referenced lesson
FamilyCore moveTimeExtra spaceStable
BubbleSwap adjacent inversionsO(n²)O(1)Yes
InsertionGrow a sorted prefixO(n²)O(1)Yes
SelectionSelect each suffix minimumO(n²)O(1)No
MergeSplit, then stably mergeO(n log n)O(n)Yes
QuickPartition around a pivotO(n log n) avg.O(log n) avg.No
CountingCount a bounded key rangeO(n + k)O(n + k)Can be
Decision referenceChoose from the constraint, not the name

Four signals choose the proof.

Read these constraints before writing a loop. They determine the invariant and the trade-off the interviewer will probe.

Stable ties?Preserve arrival order

Prefer merge sort or a stable insertion. In a merge, take the left item first on equality.

In-place?Partition the array

Quicksort trades deterministic worst-case time for compact memory and strong average performance.

Few key values?Count or band

A small integer range or three categories can produce linear time without general comparison sorting.

Almost sorted?Grow the prefix

Insertion sort adapts to existing order and can finish in linear time when no shifts are needed.