Simplify Your Workflow: Search MiniWebtool.
Add Extension
See also
Dijkstra's Shortest Path CalculatorAdjacency Matrix CalculatorNetwork Flow Calculator (Max Flow)
Home Page > Math > Advanced Math Operations > Topological Sort Calculator

Topological Sort Calculator

Compute a topological ordering of a directed acyclic graph (DAG) using Kahn's algorithm or DFS. Detects cycles, reports the cycle path, builds a parallel-execution layer view, supports lexicographically smallest ordering, and animates each step on an interactive graph.

Topological Sort Calculator
Edge format: A -> B (also accepts โ†’, =>, :). Max 80 vertices / 800 edges.
Kahn's algorithm (lexicographic) gives a unique, reproducible order. DFS post-order is the classic depth-first method.

Embed Topological Sort Calculator Widget

About Topological Sort Calculator

The Topological Sort Calculator computes a linear ordering of the vertices of a directed acyclic graph (DAG) such that every directed edge from u to v places u before v. Enter your graph as an edge list or adjacency list and the tool returns the topological order using Kahn's algorithm or DFS post-order, detects cycles (with the exact cycle path), groups tasks into parallel-execution layers, counts the number of valid orderings, and animates each step on an interactive graph.

What is a topological sort?

Given a directed graph G = (V, E), a topological sort (or topological ordering) is a linear arrangement vโ‚, vโ‚‚, โ€ฆ, vโ‚™ of its vertices such that for every directed edge (u โ†’ v), u appears before v in the arrangement. A topological ordering exists if and only if the graph has no directed cycles โ€” that is, the graph is a DAG. The ordering is rarely unique: a graph can have many valid topological sorts when several vertices have in-degree zero at the same time.

Topological order definition
A permutation (vโ‚, vโ‚‚, โ€ฆ, vn) of V is topological iff
for every edge (u โ†’ v) in E: position(u) < position(v)

Algorithms used by this calculator

Kahn's algorithm (BFS-based, 1962)

Kahn's algorithm is the most intuitive topological sort. At every step it picks a vertex with in-degree zero (no incoming edges), appends it to the output, and "removes" it from the graph by decrementing the in-degree of each of its successors. When several vertices have in-degree zero, tie-breaking can use a min-heap (giving the lexicographically smallest ordering) or a FIFO queue (giving the insertion order). Kahn's algorithm runs in O(|V| + |E|) time and doubles as a cycle detector: if any vertex still has in-degree > 0 after the queue empties, the graph has a cycle.

Kahn's algorithm (pseudocode)
Kahn(G):
  Q โ† { v โˆˆ V : indeg(v) = 0 }
  L โ† [ ]
  while Q not empty:
    u โ† Q.pop()
    L.append(u)
    for each edge u โ†’ v:
      indeg(v) -= 1
      if indeg(v) = 0: Q.push(v)
  if |L| < |V|: report cycle
  else: return L

DFS post-order (Tarjan, 1976)

The DFS algorithm runs depth-first search, and whenever a vertex finishes (i.e. all its successors have been fully explored) it is pushed onto a stack. Reversing the stack at the end yields a valid topological order. Cycle detection is natural: encountering a vertex that is still in progress (marked GRAY) means a back edge has been found, so the graph is not a DAG. DFS post-order also runs in O(|V| + |E|) time.

DFS post-order (pseudocode)
DFS-Topo(G):
  for each vertex u in V: color[u] โ† WHITE
  L โ† empty stack
  for each vertex u in V:
    if color[u] = WHITE: visit(u)
  return reverse(L)

visit(u):
  color[u] โ† GRAY
  for each edge u โ†’ v:
    if color[v] = GRAY: report cycle
    if color[v] = WHITE: visit(v)
  color[u] โ† BLACK; L.push(u)

Parallel-execution layers

A layered view of a DAG partitions its vertices into levels such that every edge goes from a lower-numbered level to a higher one. Vertices in the same layer are independent of each other, so they can be executed in parallel. The number of layers equals the length of the longest path plus one โ€” this is the critical path of the DAG, the minimum number of sequential rounds needed to finish all tasks even with unlimited parallelism. This calculator produces the layer view automatically whenever the input is a DAG.

Cycle detection

If the graph contains a directed cycle, no topological sort is possible. Our calculator reports the exact cycle path (e.g. A โ†’ B โ†’ C โ†’ A) and highlights the cycle edges in red on the visualization. Removing any single edge on the cycle is sufficient to restore acyclicity.

Input formats

Edge list

Write each directed edge as source -> target, separated by commas or newlines. Accepted arrow variants: ->, โ†’, =>, -->, :. You can also chain edges: A -> B -> C is shorthand for A->B and B->C. Vertex labels can be letters, digits, underscores, dashes, and dots.

A -> B, B -> C, A -> C
C -> D
Shirt -> Tie -> Jacket

Adjacency list

Write each vertex, a colon, and its direct successors (vertices it points to). A vertex with no successors still needs its line, such as D:.

A: B, C
B: D
C: D
D:

How to use this calculator

  1. Pick a format: Toggle between edge list and adjacency list with the radio buttons.
  2. Enter the graph: Paste your data or click one of the quick examples (dressing order, course prerequisites, build targets, a graph with a cycle, and more).
  3. Choose an algorithm: Kahn's lexicographic for a unique, reproducible order; insertion order to preserve input ordering; DFS post-order for the classic depth-first method; or Show all to see every ordering side-by-side.
  4. Click "Sort Topologically": The ordering, cycle detection, layer view, critical path length, total number of valid orderings, and an interactive graph appear below.
  5. Explore: Press Play to watch each vertex get emitted one step at a time. The in-degree badges update live. Drag any node to rearrange the layout.

Real-world applications

Build systems and compilers

Tools like make, Bazel, Gradle, and npm topologically sort their build targets so each target is compiled only after all its dependencies. A cycle in the dependency graph is usually reported as a fatal error โ€” the build system cannot decide where to start.

Task scheduling

Project managers use DAGs to capture task dependencies. The topological sort gives a valid execution order, and the layer view gives the minimum number of rounds under unlimited parallelism. The longest chain is the critical path that determines project duration.

Course prerequisite planning

A university course catalog is a DAG: edges are prerequisite relationships. A topological order is a valid study plan, and the layers tell students which sets of courses they can take in parallel during each semester.

Spreadsheet recalculation

When a cell changes, a spreadsheet must recompute every downstream cell in dependency order โ€” a topological sort of the cell-dependency DAG. Circular references (cycles) are rejected by the application.

Package managers and plugin loaders

Apt, pip, Homebrew, Maven and countless plugin frameworks resolve install or load order by topologically sorting their dependency DAGs.

Symbol resolution and instruction scheduling

Compilers use topological sort to order declarations, and CPUs use data-dependency DAGs to schedule instructions in the reorder buffer without violating data hazards.

Counting topological orderings

For a DAG with n vertices, the number of distinct valid topological orderings can range from 1 (for a totally ordered chain) to n! (for the edgeless graph). Computing the exact count is #P-complete in general, but for graphs up to 16 vertices this calculator enumerates them using a bitmask dynamic-programming formulation: f(S) = ฮฃ f(S โˆช {v}) over all v โˆ‰ S whose predecessors are all in S.

Complexity and performance

Frequently asked questions

What is a topological sort?

A topological sort of a directed acyclic graph is a linear ordering of its vertices such that every directed edge from u to v places u before v. It represents a valid order in which to process tasks that respect their dependencies.

Which algorithm does this calculator use?

The calculator runs both Kahn's algorithm and DFS post-order. Kahn's algorithm repeatedly removes a vertex with in-degree zero and decrements in-degrees of its successors. DFS post-order runs depth-first search and reverses the finish order. Both run in O(|V| + |E|) time.

What if my graph has a cycle?

A graph with a directed cycle has no topological sort. The calculator detects the cycle, highlights it in red on the visualization, and reports the exact cycle path so you can see which edges to remove to make the graph a DAG.

What is the lexicographically smallest topological order?

When many topological orderings are valid, the lexicographically smallest one is obtained by always picking the alphabetically smallest vertex whose in-degree is zero at each step. The default Kahn's mode of this calculator returns this unique ordering, which is stable and easy to reproduce.

What is the layer or level view?

The layer view groups vertices by the longest path length from any source. Vertices in the same layer have no dependency between them, so they can run in parallel. The number of layers equals the longest dependency chain plus one and gives the minimum number of parallel rounds needed to finish all tasks.

Can a graph have many valid topological orderings?

Yes. If at any step Kahn's algorithm has multiple vertices with in-degree zero, any of them can be picked next. This calculator counts the exact number of distinct topological orderings for graphs up to 16 vertices.

What is the difference between Kahn's algorithm and DFS post-order?

Kahn's works top-down: it repeatedly picks sources (in-degree 0) and emits them first. DFS post-order works bottom-up: it finishes sinks first and prepends them to the order. Both are O(|V| + |E|) and produce valid topological orderings, but typically different ones. Kahn's is easier to parallelize and to adapt for lexicographic ordering; DFS is easier to combine with other DFS-based analyses such as strongly connected components.

What is the maximum graph size this tool supports?

The calculator supports up to 80 vertices and 800 edges. Counting the total number of valid topological orderings is capped at 16 vertices because the problem is #P-complete and the state space grows as 2โฟ. The interactive visualization and algorithm animation scale smoothly up to the full size.

Further Reading

Reference this content, page, or tool as:

"Topological Sort Calculator" at https://MiniWebtool.com/topological-sort-calculator/ from MiniWebtool, https://MiniWebtool.com/

by miniwebtool team. Updated: Apr 20, 2026

You can also try our AI Math Solver GPT to solve your math problems through natural language question and answer.

Advanced Math Operations:

Top & Updated:

Instagram User ID LookupRandom Name Picker WheelRandom PickerImage ResizerFacebook User ID LookupLine CounterSort NumbersRSD Calculator - Relative Standard DeviationFPS ConverterRemove SpacesSun Position CalculatorMAC Address GeneratorWord to Phone Number Converterโฌ› Aspect Ratio Calculator๐Ÿ“ท OCR / Image to TextERA CalculatorRandom Quote GeneratorSun, Moon & Rising Sign Calculator ๐ŸŒž๐ŸŒ™โœจMAC Address Lookup๐Ÿ–ฑ๏ธ Click CounterPercent Off CalculatorMerge VideosSlope and Grade CalculatorJob FinderSquare Root (โˆš) CalculatorRandom Truth or Dare GeneratorCm to Feet and Inches ConverterWeight Loss CalculatorBatting Average CalculatorSHA256 Hash GeneratorSum CalculatorMP3 LooperVertical Jump CalculatorRandom Superpower GeneratorAdd Text to ImageRandom Credit Card GeneratorFeet and Inches to Cm ConverterNumber of Digits CalculatorBitwise CalculatorPhone Number ExtractorSalary Conversion CalculatorRandom IMEI GeneratorRandom Fake Address GeneratorRoman Numerals ConverterInvisible Text GeneratorAudio SplitterNumber to Word ConverterRandom Poker Hand GeneratorText FormatterImage SplitterRandom Writing Prompt GeneratorLog Base 10 CalculatorBinary to Gray Code ConverterIP Subnet CalculatorRandom Birthday GeneratorLunar Calendar ConverterBolt Torque CalculatorName RandomizerJulian Date ConverterCaffeine Overdose CalculatorRandom Activity GeneratorOctal CalculatorCompound Growth CalculatorHalfway Date CalculatorRandom Movie PickerFile Size ConverterDecimal to BCD ConverterLeap Years ListEmail ExtractorSHA512 Hash GeneratorStair CalculatorYouTube Channel StatisticsImage CompressorFirst n Digits of PiRandom Meal GeneratoreBay Fee CalculatorQuotient and Remainder CalculatorHebrew Calendar ConverterWAR CalculatorLong Division CalculatorWord Ladder GeneratorMaster Number CalculatorRandom Loadout GeneratorBCD to Decimal ConverterVideo CompressorCompare Two StringsFlip VideoPercent Growth Rate CalculatorMD5 Hash GeneratorBcrypt Hash Generator / CheckerList of Prime NumbersSlugging Percentage Calculator๐Ÿ“… Date CalculatorBreak Line by CharactersSocial Media Username CheckerAI Language DetectorOutlier CalculatorDMS to Decimal Degrees ConverterOn Base Percentage CalculatorAPI TesterRandom Number PickerRandomize NumbersOPS CalculatorVideo to Image Extractor๐Ÿ” Plagiarism Checker๐ŸŽฐ Gacha Pity CalculatorAdd Prefix and Suffix to TextBingo Card GeneratorPercent to PPM ConverterDay of the Year Calculator - What Day of the Year Is It Today?Modulo CalculatorWhat is my Zodiac Sign?IP Address to Hex ConverterArc Length CalculatorRandom Chord GeneratorIP Address to Binary ConverterMultiplication CalculatorYouTube Tag ExtractorAstrological Element Balance Calculator๐Ÿ”Š Tone GeneratorRandom Tournament Bracket GeneratorGray Code to Binary ConverterTime Duration CalculatorVideo SplitterRandom Emoji GeneratorBroken Link CheckerNumber ExtractorDecibel (dB) CalculatorSmall Text Generator โฝแถœแต’แต–สธ โฟ แต–แตƒหขแต—แต‰โพWord Scramble GeneratorSocial Media Post Time OptimizerAcreage CalculatorName Number CalculatorIs it a Prime Number?Estimation CalculatorMercury Retrograde CalendarLED Resistor CalculatorBattery Life CalculatorHeight Percentile CalculatorGreat Circle Distance CalculatorCone Flat Pattern (Template) GeneratorConnect the Dots GeneratorRatio CalculatorLottery Number GeneratorRandom Math Problem GeneratorRandom Object GeneratorList RandomizerMultiple Fraction CalculatorSaturn Return CalculatorWHIP CalculatorDay of Year CalendarRemove AccentURL ExtractorProportion CalculatorGolden Ratio CalculatorSquare Numbers ListBinary to BCD ConverterPartition Function CalculatorText Case ConverterRandom Line PickerHTML CompressorAm I Overweight?Image CropperRatio to Percentage CalculatorPipe Flow CalculatorColor InverterLove Compatibility CalculatorMAC Address AnalyzerPercentage Increase CalculatorChinese Gender PredictorTaco Bar CalculatorWhitespace VisualizerYouTube Thumbnail DownloaderMagic 8-BallRandom Excuse GeneratorImage EnhancerNumber Pattern FinderFirst n Digits of eRemove Line BreaksAdjust Video SpeedAngel Number Calculator๐Ÿ“Š Bar Graph MakerFraction CalculatorRandom User-Agent GeneratorAmortization CalculatorScientific Notation to Decimal ConverterSum of Positive Integers CalculatorHow Long Ago CalculatorRandom Video Thumbnail GeneratorSigma Notation Calculator (Summation)Random Chess Opening GeneratorWhat is my Lucky Number?Mcg to Mg ConverterWater Usage CalculatorEffect Size CalculatorNumber RandomizerReverse VideoLbs to Kg ConverterAI ParaphraserAI Punctuation AdderSort Lines AlphabeticallyHex to BCD ConverterBCD to Binary ConverterBCD to Hex ConverterMedian CalculatorStandard Error CalculatorAverage CalculatorPVIFA CalculatorHypotenuse CalculatorRemove Audio from VideoActual Cash Value CalculatorLog Base 2 CalculatorRoot Mean Square CalculatorSHA3-256 Hash GeneratorAI Sentence ExpanderHex to Decimal ConverterRandom Group GeneratorConvolution CalculatorRandom String GeneratorRemove Leading Trailing SpacesMarkup CalculatorPVIF CalculatorDecimal to Hex ConverterInstagram Font GeneratorSocial Media Image Size GuideTikTok Money CalculatorTwitter/X Character CounterTwitter/X Timestamp ConverterYouTube Watch Time CalculatorTwitch Earnings CalculatorYouTube Shorts Monetization CalculatorFacebook Ad Cost CalculatorSocial Media ROI CalculatorCTR CalculatorROAS CalculatorInfluencer ROI CalculatorForce CalculatorAcceleration CalculatorVelocity CalculatorMomentum CalculatorProjectile Motion CalculatorKinetic Energy CalculatorPotential Energy CalculatorWork and Power CalculatorDensity CalculatorPressure CalculatorIdeal Gas Law CalculatorFree Fall CalculatorTorque CalculatorHorsepower CalculatorDilution CalculatorChemical Equation BalancerStoichiometry CalculatorPercent Yield CalculatorEmpirical Formula CalculatorBoiling Point CalculatorTitration CalculatorMole/Gram/Particle ConverterIrregular Polygon Area CalculatorFrustum CalculatorTorus Calculator3D Distance CalculatorCircumscribed Circle (Circumcircle) CalculatorInscribed Circle (Incircle) CalculatorAngle Bisector CalculatorTangent Line to Circle CalculatorHeron's Formula CalculatorCoordinate Geometry Distance CalculatorVolume of Revolution CalculatorSurface of Revolution CalculatorParametric Curve GrapherRiemann Sum CalculatorTrapezoidal Rule CalculatorSimpson's Rule CalculatorImproper Integral CalculatorL'Hรดpital's Rule CalculatorMaclaurin Series CalculatorPower Series CalculatorSeries Convergence Test CalculatorInfinite Series Sum CalculatorAverage Rate of Change CalculatorInstantaneous Rate of Change CalculatorRelated Rates SolverOptimization Calculator (Calculus)Gradient Calculator (Multivariable)Divergence CalculatorCurl CalculatorLine Integral CalculatorSurface Integral CalculatorJacobian Matrix CalculatorNewton's Method CalculatorRREF Calculator (Row Echelon Form)Matrix Inverse CalculatorMatrix Multiplication CalculatorDot Product CalculatorCross Product CalculatorVector Magnitude CalculatorUnit Vector CalculatorAngle Between Vectors CalculatorNull Space CalculatorColumn Space CalculatorCramer's Rule CalculatorMatrix Diagonalization CalculatorQR Decomposition CalculatorCholesky Decomposition CalculatorMatrix Power CalculatorCharacteristic Polynomial CalculatorBayes' Theorem CalculatorF-Test / F-Distribution CalculatorHypergeometric Distribution CalculatorNegative Binomial Distribution CalculatorGeometric Distribution CalculatorExponential Distribution CalculatorWeibull Distribution CalculatorBeta Distribution CalculatorSpearman Rank Correlation CalculatorFisher's Exact Test CalculatorContingency Table CalculatorOdds Ratio CalculatorBernoulli Equation CalculatorAP Score CalculatorAttendance Percentage CalculatorPercentage to CGPA ConverterCitation Generator (APA/MLA/Chicago)AI Quiz GeneratorAI Lesson Plan GeneratorInteractive Periodic TableElectron Configuration CalculatorLimiting Reactant CalculatorTheoretical Yield CalculatorHenderson-Hasselbalch CalculatorpKa to Ka ConverterMolality CalculatorNormality CalculatorPercent Composition CalculatorFreezing Point Depression CalculatorBoiling Point Elevation CalculatorOsmotic Pressure CalculatorNernst Equation CalculatorBeer-Lambert Law CalculatorGravitational Force CalculatorEscape Velocity CalculatorKepler's Third Law CalculatorTime Dilation CalculatorE=mcยฒ CalculatorPhoton Energy Calculatorde Broglie Wavelength CalculatorTerminal Velocity CalculatorBuoyancy CalculatorWave Speed CalculatorSpeed of Sound CalculatorMechanical Advantage CalculatorInclined Plane CalculatorFriction CalculatorResistors in Series CalculatorWatts to Amps CalculatorAmps to Watts CalculatorkVA Calculator3-Phase Power CalculatormAh to Wh ConverterGenerator Size CalculatorLumens to Watts ConverterLux to Lumens CalculatorRoom Lighting CalculatorInductive Reactance CalculatorSeries/Parallel Capacitor CalculatorConduit Fill CalculatorAntenna Length CalculatorCubic Yard CalculatorAsphalt CalculatorSod CalculatorGrass Seed CalculatorDeck Stain CalculatorSiding CalculatorBaseboard & Trim CalculatorBaluster Spacing CalculatorEpoxy Resin CalculatorWater Heater Size CalculatorPool Volume CalculatorPool Salt CalculatorPond Volume & Liner CalculatorTV Size CalculatorTV Mounting Height CalculatorPicture Hanging Height CalculatorRug Size CalculatorCurtain Size CalculatorCeiling Fan Size CalculatorDehumidifier Size CalculatorAir Purifier CADR CalculatorFirewood Cord CalculatorCouch Fit CalculatorEngine Displacement Calculator2-Stroke Oil Mix CalculatorOctane Mix CalculatorLease Buyout CalculatorCost Per Mile CalculatorTire Load Index & Speed Rating LookupWheel Offset CalculatorWilks & DOTS CalculatorACFT Score CalculatorRowing Pace CalculatorHiking Time CalculatorBeep Test CalculatorFTP & Power Zones CalculatorRunning Age-Grading CalculatorHeart Rate Recovery CalculatorElo Rating CalculatorK/D Ratio CalculatorNet Run Rate CalculatorBatting Strike Rate CalculatorBowling Economy CalculatorDart Checkout CalculatorStableford CalculatorSpeedrun Split TimerBike Size CalculatorSnowboard Size CalculatorHat Size ConverterGlove Size CalculatorHelmet Size CalculatorSki Size CalculatorSurfboard Volume CalculatorTennis Grip Size CalculatorBackpack Size CalculatorCelsius to Fahrenheit ConverterFahrenheit to Celsius ConverterKm to Miles ConverterMiles to Km ConverterMM to Inches ConverterInches to MM ConverterStone to Kg ConverterKg to Stone ConverterLiters to Gallons ConverterGallons to Liters ConverterML to Oz ConverterOz to ML ConverterSquare Meters to Square Feet ConverterSquare Feet to Square Meters ConverterCubic Feet to Cubic Yards ConverterCubic Meters to Cubic FeetKnots to MPH ConverterMPH to KMH / KMH to MPHMg to Ml ConverterAI Text SummarizerAI TranslatorAI Story GeneratorAI Poem GeneratorAI Song Lyrics GeneratorIndian Land Unit ConverterTola to Gram ConverterPX to REM ConverterPT to PX ConverterMerge PDFSplit PDFCompress PDFPDF to JPGJPG to PDFRotate PDFDelete PDF PagesAdd Page Numbers to PDFProtect PDFReorder PDF PagesPDF Word CounterPDF Page ExtractorPDF to Text ExtractorUnlock PDF (Owner-Password Removal)PDF Flatten ToolAI Rap Lyrics GeneratorAI Cover Letter GeneratorAI Resume Bullet GeneratorAI LinkedIn Headline & Bio GeneratorAI Instagram Caption GeneratorAI YouTube Title & Description GeneratorAI Video Script GeneratorAI Product Description GeneratorAI Press Release GeneratorAI Wedding Speech GeneratorAI Thank-You Note GeneratorAI Dream InterpreterRandom Question GeneratorWould You Rather GeneratorNever Have I Ever GeneratorIcebreaker Question GeneratorCharades GeneratorPictionary Word GeneratorHangman Word GeneratorTrivia Question GeneratorRandom Fact GeneratorRandom Joke GeneratorDad Joke GeneratorPickup Line GeneratorCompliment Generator