V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Bubble Sort

Adjacent swaps that grow a sorted suffix one pass at a time

Move the largest remaining value right

Bubble Sort scans adjacent pairs from left to right. Whenever the left value is larger, the pair swaps. After one complete pass, the largest value in the unsorted prefix has moved to the end, where it will never move again.

Read the two pointers

The arrows mark the current adjacent pair. A comparison highlights both bars, a swap changes their stable positions, and the green suffix records values already fixed. Watch how one large value can move several places during a single pass.

7
6
5
10
9
8
4
3
2
1

Start pass 1; the largest remaining value will reach the unsorted suffix.

1function bubbleSort(a: number[]): number[] {
2 const n = a.length;
3 for (let end = n - 1; end > 0; end--) {
4 for (let j = 0; j < end; j++) {
5 if (a[j] > a[j + 1]) {
6 [a[j], a[j + 1]] = [a[j + 1], a[j]];
7 }
8 }
9 }
10 return a;
11}
n10
pass1
j0
a[j]7
a[j+1]6
swapCount0
sortedFrom10
1 / 145

Cost and limits

This direct version performs O(n^2) comparisons and uses O(1) auxiliary space. It is stable because equal values are never swapped. An early-exit flag can make an optimized version linear on already sorted input, but it remains a poor choice for large arrays.

Invariant: after pass p, the last p positions contain the correct largest values in sorted order.

Continue with Merge Sort to replace repeated adjacent work with structured merging, or compare all sorting costs in the complexity reference.