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

Divide and conquer docs
Divide and conquer
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
Discussions

Divide and conquer guide · 2/6

How It Works: Step-by-Step Traces

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
2right4, 5, 73
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.
Questions about this chapter?
Previous chapterDivide and Conquer: Core ConceptsNext chapterImplementation: Inversions and Fast Power

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.