跳到正文
产品桌面工具TASTECAD图纸查看TASTEFILES文件管理TASTEFTP文件传输TASTESSH远程工作空间TASTEZIP压缩与解压开发工具TASTECODERust 集成开发环境TASTESTUDIO集成开发与测试环境TASTEETL数据整合(ETL)服务器TASTEREMOTE远程桌面服务器TASTEGEO空间信息服务器TASTEMAIL邮件工作空间开始使用下载文档购买全部产品
市场
资讯
技术资讯今日开发资讯开发文档编程语言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express应用与桌面框架TauriFlutterReact NativeElectron算法算法基础核心算法进阶算法实用算法
社区项目开发日志提示词AI 工具问题作品展示社区指南
合作技术传授网站构建桌面应用构建发布与支付流水线销售合作伙伴联系我们
服务远程桌面安装包定制
TASTEDEV
产品

桌面工具

TASTECAD复杂图纸,轻松打开TASTEFILES只要需要的文件,最快送达TASTEFTP让文件往来,干净利落TASTESSH你与服务器之间,连接更牢靠TASTEZIP压得更快,解得更稳

开发工具

TASTECODE在一个窗口中完成 Rust 应用的编辑、构建、调试和测试TASTESTUDIO从编辑到远程测试,再到经批准的 AI 修复TASTEETL边看数值,边搬数据

服务器

TASTEREMOTE在自己的服务器上运行的远程桌面TASTEGEO用 Rust 重新构建兼容 GeoServer 的空间信息服务器TASTEMAIL把邮件的主导权拿回自己手中

开始使用

下载所有产品的最新版本文档各产品使用方法购买订阅与永久许可全部产品一览全部产品
全部产品
市场资讯
技术

资讯

今日开发资讯语言、框架、GitHub 与 AI 官方发布开发文档语言、框架与算法指南

编程语言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
应用与桌面框架TauriFlutterReact NativeElectron

算法

算法基础复杂度分析 · 排序 · 查找 · 基础数据结构 · 树与堆核心算法图遍历 · 最短路径与最小生成树 · 动态规划 · 贪心算法 · 分治法 · 回溯法进阶算法字符串算法 · 数学与数论 · 位运算 · 线段树 · 并查集实用算法编程面试解题策略 · LRU 缓存 · 限流 · 一致性哈希
查看全部开发文档
社区
项目发现开发者与作品开发日志决策与试错提示词可复用的指令AI 工具问题Claude、Codex、Gemini 的问题与变通办法作品展示已完成的成果社区指南我们如何公开构建
合作
技术传授用 Rust 和 egui 打造原生应用网站构建10 种语言、账户、文档与下载桌面应用构建Rust 和 egui,不用 WebView发布与支付流水线签名、MSI、deb、rpm、AppImage、哈希销售合作伙伴推荐即得 30%联系我们开发、合作与投资咨询
服务
远程桌面用浏览器连接你的电脑安装包定制只装需要的,设置预先放好
购买
ZH
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登录
登录
TASTEDEV

从小工具到更好的开发。

support@tastedev.net支持 TASTEDEV
产品产品线购买文档下载市场客户支持
社区项目开发日志提示词AI 工具问题作品展示
政策隐私政策服务条款订阅条款退款政策社区规范
账户登录注册
访客
今天
012345678901234567890123456789012345678901234567890123456789
昨天
012345678901234567890123456789012345678901234567890123456789
累计浏览
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
公司名称
GXSOFT
法定代表人
CHOI YOUNG GU
营业执照号
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
电话
+82-10-4404-1523
电子邮件
whitecalvin@tastedev.net
个人信息保护负责人
CHOI YOUNG GU

© 2026 TASTEDEV产品信息以已验证的开发源码为准。已发布·持续改进

排序 文档
排序
Sorting ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
讨论

排序 指南 · 4/6

Complexity

本章目前仅提供英文版。

Time complexity alone does not pick a sorting algorithm. You also need the gap between best, average and worst case, extra memory, stability, and sensitivity to input patterns. This chapter tabulates the main sorts, shows why comparison sorting cannot beat n log n, and explains how counting and radix sort sidestep that bound.

Comparison table

AlgorithmBestAverageWorstExtra memoryStableIn-place
Bubble sort (early exit)O(n)O(n²)O(n²)O(1)yesyes
Selection sortO(n²)O(n²)O(n²)O(1)noyes
Insertion sortO(n)O(n²)O(n²)O(1)yesyes
Merge sortO(n log n)O(n log n)O(n log n)O(n)yesno
Quicksort (random pivot)O(n log n)O(n log n)O(n²)O(log n) stacknoyes
HeapsortO(n log n)O(n log n)O(n log n)O(1)noyes
TimsortO(n)O(n log n)O(n log n)O(n)yesno
IntrosortO(n log n)O(n log n)O(n log n)O(log n)noyes
Counting sortO(n + k)O(n + k)O(n + k)O(n + k)yesno
Radix sortO(d(n + b))O(d(n + b))O(d(n + b))O(n + b)yesno

Here k is the value range, d the number of digits and b the base (values per digit). Quicksort's O(log n) stack holds only when the implementation recurses on the smaller side; naive recursion on both sides can go O(n) deep.

Analyzing merge sort and quicksort

Merge sort follows the recurrence T(n) = 2T(n/2) + O(n). Halving gives log n levels, each level merges n elements in total, so the cost is O(n log n). The split ignores the data, so best and worst case are the same.

Quicksort depends on how evenly the pivot splits the array. Even splits give O(n log n); if one side is always empty, the cost is n + (n - 1) + ... + 1 = O(n²). With a random pivot the expected number of comparisons is about 1.39 n log₂ n, a bit more than merge sort, but quicksort scans contiguous memory in place and is usually faster in practice. You can measure how badly a naive "first element as pivot" quicksort does on sorted input:

import random

def quicksort_count(a, choose):
    comparisons = 0
    stack = [(0, len(a) - 1)]
    while stack:
        lo, hi = stack.pop()
        if lo >= hi:
            continue
        p = choose(lo, hi)
        a[p], a[hi] = a[hi], a[p]
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            comparisons += 1
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        stack += [(lo, i - 1), (i + 1, hi)]
    return comparisons

n = 2000
print(quicksort_count(list(range(n)), lambda lo, hi: lo))               # 1999000 = n(n-1)/2
print(quicksort_count(list(range(n)), lambda lo, hi: random.randint(lo, hi)))  # roughly 25000

The Ω(n log n) lower bound

A comparison sort learns the order only through yes/no questions of the form "is a < b?". Drawing every possible sequence of questions gives a decision tree whose leaves correspond to permutations of the input. There are n! orderings of n distinct elements, so the tree needs at least n! leaves, and a binary tree of height h has at most 2^h leaves. Hence 2^h ≥ n!, so h ≥ log₂(n!). Since n! is at least (n/2)^(n/2), we get log₂(n!) ≥ (n/2) log₂(n/2), and the worst-case number of comparisons is Ω(n log n).

This means merge sort and heapsort are asymptotically optimal. It also means that dropping the "comparisons only" assumption can buy speed.

import math

for n in [10, 100, 1000]:
    lower = math.ceil(math.log2(math.factorial(n)))
    print(n, lower, round(n * math.log2(n)))
# 10 22 33
# 100 525 664
# 1000 8530 9966

Sorting without comparisons

Counting sort runs in O(n + k) when the value range k is comparable to n or smaller. Ages, scores from 0 to 100 and byte values are good fits; when k is huge, time and memory follow k.

Radix sort splits w-bit integers into r-bit digits and runs d = w / r stable counting passes. For 32-bit integers with 8-bit digits, d = 4 and b = 256, so the cost is 4(n + 256), effectively linear. Fixed-length strings can be sorted the same way.

def radix_sort(a, bits=32, r=8):
    mask = (1 << r) - 1
    for shift in range(0, bits, r):
        buckets = [[] for _ in range(1 << r)]
        for x in a:                      # appended in order, so each pass is stable
            buckets[(x >> shift) & mask].append(x)
        a = [x for bucket in buckets for x in bucket]
    return a

print(radix_sort([170, 45, 75, 90, 802, 24, 2, 66]))
# [2, 24, 45, 66, 75, 90, 170, 802]

This version handles non-negative integers only; negatives need the sign bit flipped or a separate pass.

Summary

  • Merge sort and heapsort are O(n log n) in the worst case; quicksort is fast on average but needs a good pivot strategy to avoid O(n²).
  • The decision-tree argument proves no comparison sort beats Ω(n log n).
  • Counting and radix sort exploit integer structure to approach linear time, paying in range limits and memory.
  • Real choices also weigh stability, extra memory and adaptivity to nearly sorted input.
对本章有疑问?
上一章Implementation下一章Practice Problems

0 条评论

热门评论最新优先

登录 · 登录后即可发表评论。