Sort a List of Versions Using Semver Rules
Sort a list of semantic versions in correct order. Learn why lexicographic sorting fails for versions and how semver comparison produces the right result.
Detailed Explanation
Sorting Versions with Semver Rules
Sorting version strings alphabetically produces wrong results. Semver-aware sorting is required to get the correct order.
Why Lexicographic Sort Fails
| Lexicographic Sort | Semver Sort |
|---|---|
1.1.0 |
1.1.0 |
1.10.0 |
1.2.0 |
1.2.0 |
1.10.0 |
1.9.0 |
1.9.0 |
2.0.0 |
2.0.0 |
Lexicographic comparison treats version components as characters, so "10" comes before "2" (because '1' < '2'). Semver comparison treats them as integers, so 10 > 2.
The Correct Sorting Algorithm
To sort a list of semver versions:
- Parse each string into
(major, minor, patch, prerelease)tuples - Sort by major (integer), then minor (integer), then patch (integer)
- Versions without pre-release come after same-numbered versions with pre-release
- Pre-release versions are compared using the identifier comparison rules
Sorting Example
Given these versions in random order:
2.0.0, 1.0.0-alpha, 1.0.0, 1.0.0-rc.1, 0.9.0, 1.0.0-beta.2, 1.1.0
Correct semver sort (ascending):
0.9.0
1.0.0-alpha
1.0.0-beta.2
1.0.0-rc.1
1.0.0
1.1.0
2.0.0
Using Batch Check for Sorting
While the main sorting use case is handled in the Compare tab, you can also use Batch Check to paste a list of versions and see them evaluated against a range. This effectively filters and highlights which versions in your list fall within a desired range.
Practical Applications
| Use Case | Example |
|---|---|
| Changelog ordering | Display releases newest-first |
| Latest version detection | Find the highest version in a list |
| Version range filtering | Show all versions matching ^1.0.0 |
| Registry browsing | Sort published versions of a package |
| Rollback selection | Find the previous stable release |
Handling Mixed Formats
When sorting versions from multiple sources, you may encounter mixed formats (v1.2.3, 1.2, 1.2.3.4). Coerce all strings to valid semver first, then sort. Versions that cannot be coerced should be placed separately to avoid incorrect ordering.
Use Case
Building release dashboards, changelog generators, or package registry UIs that need to display versions in the correct order rather than alphabetical order.
Try It — Semver Calculator
Related Topics
Compare Two Semver Versions — Which Is Newer?
Version Comparison
Coerce a Loose Version String into Valid SemVer
Validation
Validate a Semver String — Is It Valid Semantic Versioning?
Validation
Major, Minor, Patch — What Each Number Means
Version Comparison
Comparing Pre-release Versions (alpha, beta, rc)
Version Comparison