AlgoTales · Roadmap

Insert

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

Where you will meet this in real life

Inserting into a heap means adding the new item at the next free spot at the bottom and swapping it upward while it is better than its parent. Only one short path is touched, so new items can keep arriving without ever re-sorting.

Practical use cases

  • Web app: A new urgent support ticket arrives. A customer submits a ticket marked "payment failed". It joins the bottom of the waiting queue and climbs past less urgent tickets until it is correctly placed. Within a few swaps it can be first in line, while the other thousands of tickets stay where they are.
  • Web app: Live order matching for a trading app. A trading screen receives new buy offers every second. Each offer drops into a heap and moves up while its price beats the one above. The best offer is always available at the top, so the screen never lags during a busy hour.
  • System: Event simulations and streams. Simulations and game engines add new future events as they happen, and a heap keeps the next event ready. Data pipelines receiving a stream of readings use the same insert to keep the most important one on top. Each arrival costs only a few swaps.

The story: The Newcomer Who Climbed the Ladder

At the auto-rickshaw stand near Mira's house, Zoya kept a board of fare quotes, with the cheapest at the top, like a min heap. Quotes: 2, 5, 3, 9, 6, 8, 7, each hung neatly from its parent.

Suddenly a new driver shouted, "I will go for just 1!" Zoya panicked. Where does it go? Sorting everything again would take forever. "First," said Grandpa Bhaskar, "put him in the next free seat at the bottom. That keeps the board full and tidy, with no gaps."

"Now he is probably in the wrong place. So he climbs." The new quote 1 compared itself with its parent 9. Smaller, so swap. Then with 5. Smaller, swap. Then with 2. Smaller, swap! Now he sat at the top with nobody above him. Three comparisons, three swaps, done.

This is insert for a heap: add at the bottom, then sift up (also called "bubble up") until the parent is no longer bigger. A late arrival with a high number would not climb at all, because its parent is already smaller.

How to spot this problem, and where you need it

New items keep arriving while old ones are being served, and the next one to serve must always be the most important, without a full re-sort per arrival.

Signs you need it

  • You push to an array and sort it again after each arrival.
  • The task says "add an element to a priority queue" or "stream of incoming tasks".
  • Queue operations are fast with 100 items but the app stalls when thousands arrive per minute.

Where to use it in a project

  • Ticket, order and job queues where urgent items can arrive at any time.
  • Event loops and simulations that schedule future events as they discover them.

The solution

Put the new item in the first empty slot at the end of the array. Compare it with its parent, which sits at position (i minus 1) divided by 2. If the new item should be higher up (smaller in a min heap), swap them and repeat. Stop when the parent is better or you reach the top.

Payoff: Before: sorting 50,000 tickets per new arrival. After: at most about 16 swaps per arrival, usually 1 or 2.

Explain it like I am 8

A new kid joins the bottom row of a pyramid of kids. If the kid is smaller than the one directly above, they swap places. They keep swapping upwards until the kid above is smaller, or they reach the top.

How it works, step by step

  1. Append the new value at the end of the array (the next free seat).
  2. Find its parent at spot (i-1)/2 (rounded down).
  3. If the new value is smaller than its parent (min heap), swap them and continue from the parent's old spot.
  4. Stop when the parent is not bigger, or when you reach spot 0.
  5. The climb is at most the height of the tree, so an insert is quick even for a million items.

The code in four languages

PHP

<?php
// Add $x at the bottom, then climb while it is smaller than its parent (min heap).
function insert(array &$heap, int $x): void {
    $heap[] = $x;                                   // next free seat
    $i = count($heap) - 1;
    while ($i > 0) {
        $parent = intdiv($i - 1, 2);
        if ($heap[$i] >= $heap[$parent]) break;     // parent is smaller or equal: stop
        [$heap[$i], $heap[$parent]] = [$heap[$parent], $heap[$i]];   // climb one step
        $i = $parent;
    }
}

$fares = [2, 5, 3, 9, 6, 8, 7];
insert($fares, 1);
echo implode(' ', $fares), PHP_EOL;                 // 1 2 3 5 6 8 7 9  (1 climbed to the top)
insert($fares, 10);
echo implode(' ', $fares), PHP_EOL;                 // 1 2 3 5 6 8 7 9 10 (10 did not move)

JavaScript

// Add x at the bottom, then climb while it is smaller than its parent (min heap).
function insert(heap, x) {
  heap.push(x);                                     // next free seat
  let i = heap.length - 1;
  while (i > 0) {
    const parent = (i - 1) >> 1;
    if (heap[i] >= heap[parent]) break;             // parent is smaller or equal: stop
    [heap[i], heap[parent]] = [heap[parent], heap[i]];   // climb one step
    i = parent;
  }
}

const fares = [2, 5, 3, 9, 6, 8, 7];
insert(fares, 1);
console.log(fares.join(' '));                       // 1 2 3 5 6 8 7 9  (1 climbed to the top)
insert(fares, 10);
console.log(fares.join(' '));                       // 1 2 3 5 6 8 7 9 10 (10 did not move)

Java

import java.util.*;

public class Main {
    // Add x at the bottom, then climb while it is smaller than its parent (min heap).
    static void insert(List<Integer> heap, int x) {
        heap.add(x);                                    // next free seat
        int i = heap.size() - 1;
        while (i > 0) {
            int parent = (i - 1) / 2;
            if (heap.get(i) >= heap.get(parent)) break; // parent is smaller or equal: stop
            Collections.swap(heap, i, parent);          // climb one step
            i = parent;
        }
    }

    public static void main(String[] args) {
        List<Integer> fares = new ArrayList<>(List.of(2, 5, 3, 9, 6, 8, 7));
        insert(fares, 1);
        System.out.println(fares);                      // [1, 2, 3, 5, 6, 8, 7, 9]  (1 climbed to the top)
        insert(fares, 10);
        System.out.println(fares);                      // [1, 2, 3, 5, 6, 8, 7, 9, 10] (10 did not move)
    }
}

Go

package main

import "fmt"

// insert adds x at the bottom, then climbs while it is smaller than its parent (min heap).
func insert(heap []int, x int) []int {
	heap = append(heap, x) // next free seat
	i := len(heap) - 1
	for i > 0 {
		parent := (i - 1) / 2
		if heap[i] >= heap[parent] { // parent is smaller or equal: stop
			break
		}
		heap[i], heap[parent] = heap[parent], heap[i] // climb one step
		i = parent
	}
	return heap
}

func main() {
	fares := []int{2, 5, 3, 9, 6, 8, 7}
	fares = insert(fares, 1)
	fmt.Println(fares) // [1 2 3 5 6 8 7 9]  (1 climbed to the top)
	fares = insert(fares, 10)
	fmt.Println(fares) // [1 2 3 5 6 8 7 9 10] (10 did not move)
}

Time: O(log n) · Extra space: O(1). At most one swap per level on the way up, and the tree is only about log n levels tall.

Watch out for

  • Inserting at the top and sinking. The standard way is to add at the bottom (end of the array) and climb.
  • Comparing with a sibling instead of the parent. Only the parent matters when climbing.
  • Using > instead of >= in the stop check and swapping equal values forever for no reason. Equal is already fine, so stop.

Quick check

  1. Where does a new value go first?
    • In the middle
    • At the root
    • At the next free seat at the bottom
  2. When does the climbing stop (min heap)?
    • When the parent is smaller or equal
    • After 3 steps
    • When it becomes the right child
  3. How many levels can a new value climb at most?
    • Up to the root: about log n levels
    • Exactly one
    • All n items