Video yükleniyor...
Video Yüklenemedi
This animation shows how insertion sort works for an array of size 50.
62,493 görüntüleme • 6 ay önce •via X (Twitter)
7 Yorum

made a little tool some time ago to visualise more of them.

void insertionSort(int[] a) { int n = a.length; for (int i = 1; i < n; i++) { int j = i; while (j > 0 && a[j - 1] > a[j]) { int t = a[j]; a[j] = a[j - 1]; a[j - 1] = t; j--; } } } ------- For N=50 (worst-case reverse sorted input): Comparisons: ~1,225 Assignments/swaps: ~1,225 * 3 Increments/decrements: ~1,225 Total operations ≈ 6,125 ================ void insertionSortBranchless(int[] a) { int n = a.length; for (int i = 1; i < n; i++) { // FIXED-1.1.1: outer bound only (no inner cond) int j = i; // Branchless inner: always iterate max possible, predicate moves with sign masks for (int k = 0; k < i; k++) { // FIXED-2.3.1: fixed bound, no while int jm1 = j - 1; int diff = a[jm1] - a[j]; // FIXED-3.2.1 int mask = diff >> 31; // 0xFFFFFFFF if a[jm1] > a[j], else 0 (branchless compare) int t = a[j]; a[j] = (a[j] & ~mask) | (a[jm1] & mask); // predicated a[jm1] = (a[jm1] & ~mask) | (t & mask); j = jm1; // always decrement position (predicated effect via mask) } } } ----------- Ops Count (N=50 worst-case): Outer: 49 iterations Inner: Σ(1..49) = 1,225 fixed iterations Per iteration: 1 sub, 1 shift, 4 bitwise AND/OR, 2 array reads, 2 writes, 1 dec → 12 ops Total operations ≈ 1,225 * 12 + 49*3 ≈ 14,800 ============= import java.util.Arrays; void optimizedSort(int[] a) { Arrays.sort(a); // FIXED-1.1.1: Library Timsort (hybrid insertion + merge/quick) } Exact same end result as original insertionSort for any input. Ops for N=50 (same random dataset class as original viz): ≈1,450 Ops

And this video explains it in detail

@ThePrimeagen

This is why algorithm choice matters—same task, totally different efficiency depending on approach.

I remember writing this in c++ as a school project.

absolute bop
Benzer Videolar
Bubble Sort vs Insertion Sort Comparing Two Algorithms
S.T.E.M Explorer
79,808 görüntüleme • 7 ay önce

