Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Sorting docs
Sorting
Sorting ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Discussions

Sorting guide · 6/6

Real-World Use

You will rarely implement a sorting algorithm at work. What matters is knowing which algorithm your language uses, whether it is stable, and how to pass comparators safely. This chapter covers the built-in sorts of major languages, common pitfalls, and tools that can replace a full sort.

Built-in sorts by language

Language and functionAlgorithmStable
Python sorted, list.sortTimsortyes
Java Arrays.sort (primitive arrays)Dual-Pivot Quicksortnot applicable
Java Arrays.sort (object arrays), List.sortTimSortyes
C++ std::sortimplementation-defined, usually introsort-basedno
C++ std::stable_sortmerge sortyes
JavaScript Array.prototype.sortnot specified (V8 uses TimSort)yes (required since ES2019)
Go sort.Sort, slices.Sortpdqsort (sort since Go 1.19)no

Python's Timsort finds runs that are already sorted, extends short runs with binary insertion sort, and then merges runs. When one side keeps winning, galloping mode skips ahead with exponential search. That makes it very fast on sorted or nearly sorted data and on two sorted lists concatenated together. CPython 3.11 replaced the rule that decides the merge order with the Powersort policy, but stability and the O(n log n) worst case are unchanged. Java's object sort is a port of Python's Timsort.

The C++ standard does not prescribe an algorithm for std::sort; since C++11 it only requires O(n log n) comparisons. Major implementations such as libstdc++ use introsort: start with quicksort, switch to heapsort when recursion gets deeper than about 2 log n, and finish small ranges with insertion sort. When you need stability, use std::stable_sort.

When you do not need a full sort

If you only need part of the order, cheaper tools exist.

import heapq

scores = [72, 95, 88, 61, 99, 85, 90, 77]
print(heapq.nlargest(3, scores))   # [99, 95, 90]  O(n log k)
print(heapq.nsmallest(2, scores))  # [61, 72]

import bisect
ranked = sorted(scores)
bisect.insort(ranked, 93)          # insert while keeping the list sorted
print(ranked[bisect.bisect_left(ranked, 90):])  # 90 and above: [90, 93, 95, 99]

In C++, std::partial_sort sorts only the first k elements, and std::nth_element places the k-th element correctly and partitions around it in average O(n), which is ideal for medians and percentiles.

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{72, 95, 88, 61, 99, 85, 90, 77};
    std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
    std::cout << "median-ish: " << v[v.size() / 2] << '\n';  // 88
    std::partial_sort(v.begin(), v.begin() + 3, v.end(), std::greater<int>());
    std::cout << v[0] << ' ' << v[1] << ' ' << v[2] << '\n';  // 99 95 90
}

Databases avoid sorting for ORDER BY when an index already provides the order, and fall back to external merge sort, sorting chunks to disk and merging them, when the result does not fit in memory. The Unix sort command handles huge log files the same way.

Common pitfalls

  • JavaScript's default sort compares elements as strings: [10, 9, 1].sort() gives [1, 10, 9]. Always pass (a, b) => a - b for numbers.
  • An inconsistent comparator (not transitive, or random) produces garbage, and in Java can throw IllegalArgumentException: Comparison method violates its general contract!.
  • In Java, (a, b) -> a - b overflows for large values. Use Integer.compare or Comparator.comparingInt.
  • NaN compares false against everything and corrupts the result. Filter it out or handle it in the key.
  • Human-friendly string order is not code point order. For case, accents and language rules, use locale-aware comparison such as Intl.Collator or ICU.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Ranking {
    record Player(String name, int score) {}

    public static void main(String[] args) {
        List<Player> players = new ArrayList<>(List.of(
            new Player("lee", 90), new Player("kim", 95), new Player("park", 90)));
        players.sort(Comparator.comparingInt(Player::score).reversed()
                .thenComparing(Player::name));
        System.out.println(players);  // kim 95, lee 90, park 90
    }
}
const nums = [10, 9, 1];
console.log([...nums].sort());                // [1, 10, 9] string comparison
console.log([...nums].sort((a, b) => a - b)); // [1, 9, 10]

const names = ["Émile", "zoe", "Adam"];
console.log([...names].sort(new Intl.Collator("fr").compare)); // ["Adam", "Émile", "zoe"]

Further reading

  • Sorting Techniques (Python docs)
  • CPython listsort.txt: Timsort design notes
  • std::sort (cppreference)
  • Arrays (Java SE 21 API)
  • Array.prototype.sort() (MDN)
  • VisuAlgo: sorting visualizations

Summary

  • Knowing your built-in sort's algorithm and stability covers most practical needs.
  • For top-k, medians and keeping data sorted, heaps, selection and binary search beat a full sort.
  • Comparator consistency, numeric versus string comparison, NaN and locale rules cause most sorting bugs.
Questions about this chapter?
Previous chapterPractice Problems

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.