Zum Hauptinhalt springen
ProdukteDesktop-WerkzeugeTASTECADZeichnungsprüfungTASTEFILESDateiverwaltungTASTEFTPDateiübertragungTASTESSHRemote-ArbeitsbereichTASTEZIPKomprimieren und EntpackenTASTEWINMDateiverwaltungEntwicklerwerkzeugeTASTECODEIntegrierte Entwicklungsumgebung für RustTASTESTUDIOIntegrierte Entwicklungs- und TestumgebungTASTEETLDatenintegration (ETL)ServerTASTEREMOTERemote-Desktop-ServerTASTEGEOGeodatenserverTASTEMAILE-Mail-ArbeitsbereichInvestierenTASTESTOCKDesktop-App für automatischen AktienhandelErste SchritteDownloadsDokumentationKaufenAlle Produkte
Marktplatz
Neuigkeiten
TechnikNeuigkeitenEntwickler-News von heuteEntwicklerdokuProgrammiersprachenRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp- & Desktop-FrameworksTauriFlutterReact NativeElectronAlgorithmenAlgorithmus-GrundlagenKernalgorithmenFortgeschrittene AlgorithmenAlgorithmen für die Praxis
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcaseCommunity-Leitfaden
ZusammenarbeitWissenstransferWebsite-AufbauDesktop-App-AufbauRelease- und ZahlungspipelineVertriebspartnerKontakt
DiensteRemote-DesktopIndividuelle Installationspakete
TASTEDEV
Produkte

Desktop-Werkzeuge

TASTECADKomplexe Zeichnungen, mühelos geöffnetTASTEFILESNur die Dateien, die zählen – in BestzeitTASTEFTPDer aufgeräumteste Weg für Ihre DateienTASTESSHDie stärkere Verbindung zu Ihren ServernTASTEZIPSchneller packen, sicherer entpackenTASTEWINMEin tastaturorientierter Dateimanager mit zwei Fenstern

Entwicklerwerkzeuge

TASTECODERust-Apps bearbeiten, bauen, debuggen und testen – alles in einem FensterTASTESTUDIOVom Bearbeiten bis zu Remote-Tests und freigegebenen KI-KorrekturenTASTEETLDaten bewegen, die Werte im Blick

Server

TASTEREMOTEEin Remote-Desktop auf Ihrem eigenen ServerTASTEGEOEin GeoServer-kompatibler Geodatenserver, neu aufgebaut in RustTASTEMAILIhre E-Mail wieder in Ihrer Hand

Investieren

TASTESTOCKAutomatischer Aktienhandel nach Ihren Regeln: wann und was

Erste Schritte

DownloadsNeueste Versionen aller ProdukteDokuSo nutzen Sie jedes ProduktKaufenAbos und DauerlizenzenAlle ProdukteAlle Produkte im Überblick
Alle Produkte
MarktplatzNeuigkeiten
Technik

Neuigkeiten

Entwickler-News von heuteOffizielle Meldungen zu Sprachen, Frameworks, GitHub und KIEntwicklerdokuAnleitungen zu Sprachen, Frameworks und Algorithmen

Programmiersprachen

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App- & Desktop-FrameworksTauriFlutterReact NativeElectron

Algorithmen

Algorithmus-GrundlagenKomplexitätsanalyse · Sortieren · Suchen · Grundlegende Datenstrukturen · Bäume und HeapsKernalgorithmenGraphtraversierung · Kürzeste Wege und minimale Spannbäume · Dynamische Programmierung · Greedy-Algorithmen · Teile und herrsche · BacktrackingFortgeschrittene AlgorithmenZeichenkettenalgorithmen · Mathematik und Zahlentheorie · Bitmanipulation · Segmentbäume · Union-FindAlgorithmen für die PraxisStrategie für Coding-Interviews · LRU-Cache · Rate Limiting · Konsistentes Hashing
Alle Entwicklungsdokumente
Community
ProjekteEntwickler und Projekte entdeckenEntwicklungslogsEntscheidungen und ErkenntnissePromptsWiederverwendbare AnweisungenProbleme mit KI-ToolsProbleme und Workarounds für Claude, Codex, GeminiShowcaseFertige ErgebnisseCommunity-LeitfadenWie wir offen entwickeln
Zusammenarbeit
WissenstransferNative Apps mit Rust und eguiWebsite-Aufbau10 Sprachen, Konten, Dokumentation und DownloadsDesktop-App-AufbauRust und egui, ohne WebViewRelease- und ZahlungspipelineSignatur, MSI, deb, rpm, AppImage, PrüfsummenVertriebspartnerEmpfehlen und 30 % erhaltenKontaktEntwicklung, Partnerschaft, Investition
Dienste
Remote-DesktopIhren Computer im Browser erreichenIndividuelle InstallationspaketeNur nötige Funktionen, Einstellungen vorab
Kaufen
DE
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Anmelden
Anmelden
TASTEDEV

Von kleinen Werkzeugen zu besserer Entwicklung.

support@tastedev.netTASTEDEV unterstützen
ProdukteProduktübersichtKaufenDokuDownloadsMarktplatzSupport
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcase
RichtlinienÜber unsDatenschutzerklärungNutzungsbedingungenAbo-BedingungenRückerstattungCommunity-Richtlinien
KontoAnmeldenRegistrieren
Besucher
Heute
Gestern
Aufrufe gesamt
Firma
GXSOFT
Vertretungsberechtigt
CHOI YOUNG GU
Handelsregisternummer
853-44-00368
Anschrift
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefon
+82-10-4404-1523
E-Mail
whitecalvin@tastedev.net
Datenschutzbeauftragter
CHOI YOUNG GU

© 2026 TASTEDEVProduktinformationen basieren auf verifizierten Entwicklungsquellen.Veröffentlicht · wird verbessert

Teile und herrsche-Dokumentation
Teile und herrsche
Divide and Conquer: Core ConceptsHow It Works: Step-by-Step TracesImplementation: Inversions and Fast PowerComplexity: Recurrences and the Master TheoremPractice ProblemsDivide and Conquer in the Real World
Diskussionen

Teile und herrsche-Anleitung · 2/6

How It Works: Step-by-Step Traces

Dieses Kapitel ist vorerst nur auf Englisch verfügbar.

This chapter traces four algorithms by hand on small inputs: merge sort, counting inversions during the merge, fast exponentiation and quickselect. Working through the traces once makes the code in the next chapter easy to follow.

Merge sort on eight numbers

Take [5, 2, 4, 7, 1, 3, 2, 6]. The array is cut in half until every piece holds one element, then the pieces are merged back level by level.

LevelPieces after merging
0 (single elements)[5] [2] [4] [7] [1] [3] [2] [6]
1[2, 5] [4, 7] [1, 3] [2, 6]
2[2, 4, 5, 7] [1, 2, 3, 6]
3[1, 2, 2, 3, 4, 5, 6, 7]

Every level touches each element once, and there are log2 8 = 3 levels: that is where O(n log n) comes from. The merge compares the front elements of two sorted lists and repeatedly takes the smaller one.

def merge(left, right):
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:    # <= keeps equal elements in order (stable)
            out.append(left[i])
            i += 1
        else:
            out.append(right[j])
            j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out

print(merge([2, 4, 5, 7], [1, 2, 3, 6]))  # [1, 2, 2, 3, 4, 5, 6, 7]

Counting inversions during the merge

An inversion is a pair of positions i < j with a[i] > a[j]. Checking every pair costs O(n^2). Divide and conquer sorts inversions into three kinds: both elements in the left half, both in the right half, or one on each side (crossing). The first two kinds are counted recursively. Crossing pairs come almost for free during the merge: when right[j] is taken before left[i], it is smaller than left[i] and every element after it in the left list, so it forms len(left) - i crossing inversions.

The final merge of the trace above, [2, 4, 5, 7] with [1, 2, 3, 6]:

TakenFromLeft elements still waitingAdded
1right2, 4, 5, 74
2left-0
2right
Fragen zu diesem Kapitel?
Vorheriges KapitelDivide and Conquer: Core ConceptsNächstes KapitelImplementation: Inversions and Fast Power
4, 5, 7
3
3right4, 5, 73
4left-0
5left-0
6right71
7left-0

The final merge adds 11. The lower levels add 1 for [5] with [2], 1 for [2, 5] with [4, 7] (4 is less than 5) and 1 for [1, 3] with [2, 6] (2 is less than 3). The array therefore has 14 inversions. Because the tie 2 <= 2 takes the left element first, equal values are never counted.

Fast exponentiation

Multiplying b by itself e - 1 times is hopeless when e is large. Halve the exponent instead: b^e = (b^(e/2))^2 when e is even, and b^e = (b^((e-1)/2))^2 * b when e is odd. Each call halves e, so at most about 2 log2 e multiplications are needed.

Trace for 3^13 (13 is 1101 in binary):

CallHalf resultComputationValue
power(3, 0)-base case1
power(3, 1)11 * 1 * 33
power(3, 3)33 * 3 * 327
power(3, 6)2727 * 27729
power(3, 13)729729 * 729 * 31594323
def power(b, e):
    if e == 0:
        return 1
    half = power(b, e // 2)
    return half * half * b if e % 2 else half * half

print(power(3, 13))  # 1594323

Five calls replace twelve multiplications; for e = 10^18 it is about 60 calls instead of 10^18 steps.

Quickselect

Quickselect finds the k-th smallest element (0-based) without sorting everything. It partitions around a pivot as quicksort does, then continues only in the side that contains position k.

Trace with the last element as pivot, a = [7, 2, 9, 4, 1, 8, 3], k = 3:

RangePivotRange after partitionPivot positionNext
0..63[2, 1, 3, 4, 7, 8, 9]2k is to the right: 3..6
3..69[4, 7, 8, 9]6k is to the left: 3..5
3..58[4, 7, 8]5k is to the left: 3..4
3..47[4, 7]4k is to the left: 3..3
3..3-[4]-answer 4

After the first step each partition peels off a single element. That is exactly how the O(n^2) worst case arises with a poor pivot. A random pivot makes long runs like this unlikely and gives O(n) expected time.

import random

def quickselect(a, k):
    """k-th smallest (0-based) element of a; reorders a in place."""
    lo, hi = 0, len(a) - 1
    while lo < hi:
        p = random.randint(lo, hi)        # random pivot
        a[p], a[hi] = a[hi], a[p]
        pivot, store = a[hi], lo
        for i in range(lo, hi):           # Lomuto partition
            if a[i] < pivot:
                a[i], a[store] = a[store], a[i]
                store += 1
        a[store], a[hi] = a[hi], a[store]
        if k == store:
            return a[k]
        if k < store:
            hi = store - 1
        else:
            lo = store + 1
    return a[k]

print(quickselect([7, 2, 9, 4, 1, 8, 3], 3))  # 4

Summary

  • Merge sort does its real work in the merge: log n levels of O(n) work each.
  • Crossing inversions are counted with len(left) - i whenever the right side wins.
  • Fast exponentiation halves the exponent and needs only O(log e) multiplications.
  • Quickselect continues in one side only; random pivots keep it at O(n) expected time.

0 Kommentare

Top-KommentareNeueste zuerst

Anmelden · Melde dich an, um einen Kommentar zu schreiben.