Binary Insertion Sort
Insertion sort using binary search to find insertion position, reducing comparisons to O(n log n).
Visualization
Interactive visualization for Binary Insertion Sort
Interactive visualization with step-by-step execution
Implementation
1function binaryInsertionSort(arr: number[]): number[] {
2 const a = [...arr];
3 for (let i = 1; i < a.length; i++) {
4 const key = a[i];
5 let l = 0, r = i;
6 while (l < r) {
7 const m = (l + r) >> 1;
8 if (a[m] > key) r = m; else l = m + 1;
9 }
10 for (let j = i; j > l; j--) a[j] = a[j - 1];
11 a[l] = key;
12 }
13 return a;
14}Deep Dive
Theoretical Foundation
Uses binary search to find correct position in sorted portion, reducing comparisons from O(n²) to O(n log n), but shifts still O(n²).
Complexity
Time
O(n log n) comparisons, O(n) shifts
O(n²)
O(n²)
Space
O(1)
Applications
Industry Use
Small datasets
When comparisons are expensive
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.