Skip to main content
Level: BasicArray & Sorting

Interactive Sorting Algorithms Visualizer

Step through Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, and Quick Sort with real-time bar animations, sound synthesis, Big-O metrics, custom array input, and multi-language code snippets.

Coding ChallengesPlayground
Showing 9 modules for all level
Step Scrubber:0 / 0 (0%)
Presets:
Step: 0 / 0
Comparisons: 0
Swaps / Shifts: 0
Compare Swap Pivot Sorted
💡 Ready.

Bubble Sort (Level: Basic)

Repeatedly compares adjacent items in the array and swaps them if out of order. With each pass, the highest unsorted value bubbles up to its final position.

Best Case Time
O(n)
Average Time
O(n²)
Worst Case Time
O(n²)
Auxiliary Space
O(1)

Real-World Scenario Datasets & Examples

1-Click Load into Simulation

Test the algorithm against authentic scenarios to observe how distribution, duplicates, and ordering patterns alter operational efficiency.

E-Commerce Prices ($)
Product prices ranging from budget items to luxury tech
[19, 99, 49, 12, 199, 89, 29, 149, 69, 39]
Student Exam Scores (%)
Test percentages across a university cohort
[74, 92, 58, 88, 63, 95, 42, 81, 67, 90]
Server Ping Latencies (ms)
Network response round-trip timings
[45, 120, 18, 240, 32, 95, 12, 180, 56, 82]
Nearly Sorted Subarray
Almost sorted array with only 2 elements out of order
[10, 20, 25, 45, 35, 50, 65, 60, 80, 90]
Reversed Array (Worst Case)
Descending order testing worst-case inversion count
[95, 85, 75, 65, 55, 45, 35, 25, 15, 5]

Conceptual Breakdown: How It Works

  • 1Comparative sorting inspects pairs of elements and rearranges them according to an ordering relation (< or >).
  • 2Elementary algorithms (Bubble, Selection, Insertion) achieve O(n²) worst-case time by repeatedly checking adjacent or minimal elements.
  • 3Divide-and-conquer algorithms (Merge Sort, Quick Sort) split problems into smaller subproblems to achieve optimal O(n log n) average time complexity.
  • 4Stability means equal elements retain their relative original order, vital for multi-key database sorting.

Mathematical Invariants & Guarantees

An algorithm invariant is a condition that remains strictly true before and after every iteration. Understanding invariants is the secret to acing FAANG interview proofs.

  • ✦Bubble Sort Invariant: After pass k, the k largest elements are guaranteed to be in their final sorted positions at the right boundary.
  • ✦Selection Sort Invariant: The left subarray arr[0...k] contains the k smallest elements in sorted order.
  • ✦Insertion Sort Invariant: Subarray arr[0...k] is always internally sorted at the end of each iteration.
  • ✦Quick Sort Invariant: Once partitioned, the pivot element resides in its immutable permanent index.

Algorithm Pseudocode & Step Invariant

Formal Logic Representation
1procedure sortArray(arr):
2 for i from 0 to n - 1:
3 for j from 0 to n - i - 1:
4 if arr[j] > arr[j + 1]:
5 swap(arr[j], arr[j + 1])
6 return arr

Top FAANG & LeetCode Interview Tips

  • ✔When asked to sort in O(n log n) with O(1) auxiliary space, think Heap Sort (or in-place Quick Sort with randomized pivot).
  • ✔Always mention stability if sorting objects with multiple attributes (e.g., sorting users by age, then by name).
  • ✔Watch out for Quick Sort's worst case O(n²) when picking the first or last element of an already sorted array. Mention 3-way partitioning or randomized pivot to counter this.
  • ✔For small arrays (n ≤ 16), production runtimes like V8 and Java combine Quick/Merge Sort with Insertion Sort (Timsort / Dual-Pivot Quicksort).

Common Pitfalls & Edge Cases to Test

  • ⚠Assuming Quick Sort is always O(n log n) without accounting for skewed pivot degradation.
  • ⚠Confusing Auxiliary Space with Total Space (e.g. Merge Sort takes O(n) auxiliary memory for temporary merge buffers).
  • ⚠Overlooking stability requirements when sorting non-primitive objects.

Frequently Asked Questions (DSA Deep Dive)

Merge Sort does not require random memory access (which linked lists lack) and can merge linked sublists in O(1) extra space simply by rewiring node pointers. Quick Sort relies heavily on random index access and swaps.

Source Code Implementation

Clean, production-ready code with standard algorithmic design in 4 languages.

// Quick Sort & Merge Sort in JavaScript (ES6)
export function quickSort(arr, low = 0, high = arr.length - 1) {
  if (low < high) {
    const pivotIdx = partition(arr, low, high);
    quickSort(arr, low, pivotIdx - 1);
    quickSort(arr, pivotIdx + 1, high);
  }
  return arr;
}

function partition(arr, low, high) {
  const pivot = arr[high];
  let i = low - 1;
  for (let j = low; j < high; j++) {
    if (arr[j] <= pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }
  [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
  return i + 1;
}

Algorithm & Data Structure Complexity Matrix

Comprehensive reference of Best, Average, and Worst-Case time and space bounds.

17 Total Evaluated Systems
Algorithm / StructureLevelBest TimeAverage TimeWorst TimeSpaceStableIn-Place
Bubble SortBasicO(n)O(n²)O(n²)O(1)YesYes
Selection SortBasicO(n²)O(n²)O(n²)O(1)NoYes
Insertion SortBasicO(n)O(n²)O(n²)O(1)YesYes
Linear SearchBasicO(1)O(n)O(n)O(1)N/AYes
Binary SearchBasicO(1)O(log n)O(log n)O(1)N/AYes
Stack (Push/Pop)BasicO(1)O(1)O(1)O(n)N/AYes
Queue (Enqueue/Dequeue)BasicO(1)O(1)O(1)O(n)N/AYes
Singly Linked ListBasicO(1) headO(n) searchO(n)O(n)N/AYes
Merge SortIntermediateO(n log n)O(n log n)O(n log n)O(n)YesNo
Quick SortIntermediateO(n log n)O(n log n)O(n²)O(log n)NoYes
Binary Search Tree (BST)IntermediateO(log n)O(log n)O(n)O(n)N/AYes
Hash Table (Chaining)IntermediateO(1)O(1)O(n)O(n)N/AYes
Doubly Linked ListIntermediateO(1) endsO(n) searchO(n)O(n)N/AYes
Graph BFS / DFSAdvancedO(V + E)O(V + E)O(V + E)O(V)N/ANo
Binary Heap (Insert/Extract)AdvancedO(1) peekO(log n)O(log n)O(n)NoYes
Kadane's Algorithm (DP)AdvancedO(n)O(n)O(n)O(1)N/AYes
Fibonacci (DP Tabulation)AdvancedO(n)O(n)O(n)O(n) or O(1)N/AYes

Where Are These Data Structures Used in Real-World Production Systems?

Top tech companies (Google, Meta, Amazon, Netflix) rely on these foundations for high-scale systems:

Sorting Algorithms

Basic
  • V8 JavaScript Engine: Uses TimSort (hybrid of Merge Sort & Insertion Sort) for Array.prototype.sort().
  • Database Query Planners: ORDER BY statements in PostgreSQL and MySQL rely on external merge sorts for big tables.
  • Graphics Rendering: Z-buffering and painters algorithm sort depth layers before drawing pixels.
  • E-commerce Catalogs: Sorting millions of products by price, ratings, and relevance in milliseconds.

Binary Search

Basic
  • Database B-Tree Indices: Instant O(log n) lookups across billions of storage page rows.
  • Git Bisect: Pinpoints the exact regression commit introducing a bug in a codebase via binary chop.
  • Network IP Routing: Finding longest prefix matches in core internet routing tables.
  • Game Engine Physics: Fast collision detection and spatial partition bounding box intersections.

Stacks & Queues

Basic
  • Event Pipelines: Apache Kafka, RabbitMQ, and AWS SQS message broker message delivery queues.
  • Browser Engine: History navigation back/forward stacks, undo/redo buffers in code editors.
  • OS Kernel Scheduler: Round-Robin process dispatching and CPU interrupt priority queues.
  • Compilers: Call stack frames, expression evaluation, and syntax bracket balancing.

Linked Lists

Basic
  • LRU Caching: Combined with Hash Maps (std::map + Doubly Linked List) in Redis & web browsers.
  • Operating System Kernels: Free-memory block tracking and file allocation tables.
  • Media Players: Seamless next / previous playlist track traversal.
  • Blockchain: Immutable sequence of cryptographically linked ledger transaction blocks.

Binary Search Trees (BST)

Intermediate
  • Linux Kernel: Red-Black Trees (self-balancing BST) manage completely fair CPU scheduling (CFS).
  • Database Systems: MySQL InnoDB and SQLite indices implement balanced search trees for range queries.
  • File Systems: Ext4 and NTFS directories store filenames in tree structures for rapid lookups.
  • Auto-complete & Spellcheck: Prefix search trees and dynamic dictionary lookups.

Hash Tables

Intermediate
  • Redis & Memcached: In-memory distributed key-value data stores powering global websites.
  • Compiler Symbol Tables: Compilers map identifier names to type declarations and memory offsets.
  • Cryptographic Passwords: Salted hashing verification (bcrypt, Argon2) and token lookups.
  • Network NAT Routers: Translating public IP/ports to private local LAN addresses in real time.

Graph Algorithms (BFS & DFS)

Advanced
  • GPS Navigation: Google Maps, Waze, and Uber routing vehicles using Dijkstra / A* graph algorithms.
  • Social Networks: Facebook/LinkedIn friend suggestions via BFS degrees of separation.
  • Web Crawlers: Googlebot traverses hyperlinks across the world wide web via BFS/DFS queues.
  • Garbage Collection: Java V8 mark-and-sweep GC traverses object reference graphs to free dead memory.

Heaps & Priority Queues

Advanced
  • Bandwidth Throttling: Network routers prioritize VoIP / video packets over bulk file downloads.
  • A* Pathfinding: Priority queue of open nodes ordered by heuristic distance in game AI.
  • Median Finding: Two heaps (min-heap + max-heap) maintain real-time running median in O(1).
  • Huffman Coding: Lossless data compression in JPEG, MP3, and Gzip file archives.

Dynamic Programming (DP)

Advanced
  • Diff Algorithms: Git diff and GitHub pull request diff viewer use LCS (Longest Common Subsequence).
  • Bioinformatics: DNA and RNA sequence alignment (Needleman-Wunsch & Smith-Waterman algorithms).
  • Financial Portfolio Optimization: Dynamic asset allocation and capital budgeting under constraints.
  • Speech Recognition: Hidden Markov Models and Viterbi algorithm for acoustic word recognition.
Apply Your Knowledge

Practice Algorithm Challenges with Automated Tests

Solve LeetCode-style algorithm problems with automated test runners, time/memory execution checks, and instant evaluation in JavaScript and Python.

Practice 50+ Coding Challenges