Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoTASTEWINMGerenciamento de arquivosFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailInvestimentosTASTESTOCKAplicativo desktop de negociação automática de açõesComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurançaTASTEWINMUm gerenciador de arquivos de dois painéis feito para o teclado

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Investimentos

TASTESTOCKNegociação automática de ações pelas regras que você define: quando e o quê

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasSobre nósPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
Ontem
Visualizações totais
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de Busca
Busca
Searching ConceptsHow It WorksImplementationComplexityPractice ProblemsSearching in the Real World
Discussões

Guia de Busca · 2/6

How It Works

Por enquanto, este capítulo está disponível apenas em inglês.

This chapter follows binary search step by step on small arrays to show exactly how the range shrinks. We trace a plain value search, lower_bound and upper_bound, a search on the answer, and ternary search. The key idea throughout is the invariant: the answer always lies inside the current range.

Tracing a value search

Search for 23 in the sorted array a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] (indices 0 to 9), using the closed interval [lo, hi] and mid = (lo + hi) // 2.

Steplohimida[mid]Decision
10941616 < 23, go right: lo = 5
25975656 > 23, go left: hi = 6
356523equal, return index 5

Three comparisons for ten elements. Searching for the missing value 24 instead, the fourth step leaves lo = 6, hi = 5: the range is empty, the loop stops, and the function returns -1. An empty range is the proof that the value is absent.

Tracing lower_bound

Now compute lower_bound(2), the first index with a[i] >= 2, in a = [1, 2, 2, 2, 3, 5], which contains duplicates. We use the half-open interval [lo, hi) starting at lo = 0, hi = 6. There is a single rule: if a[mid] < x, the answer lies right of mid, so lo = mid + 1; otherwise mid itself may be the answer, so hi = mid.

Steplohimida[mid]a[mid] < 2 ?Next
10632nohi = 3
20312nohi = 1
30101yeslo = 1
end11---return 1

For upper_bound(2) only the comparison changes, to a[mid] <= x. On the same array it visits mid = 3 (value 2, so lo = 4), mid = 5 (value 5, so hi = 5), mid = 4 (value 3, so hi = 4) and returns 4. The value 2 therefore occurs times.

Dúvidas sobre este capítulo?
Capítulo anteriorSearching ConceptsPróximo capítuloImplementation
4 - 1 = 3

The code below prints that trace. Try other arrays and targets and check them against tables you draw by hand; it is the fastest way to internalize the boundary handling.

def lower_bound_trace(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        go_right = a[mid] < x
        print(f"lo={lo} hi={hi} mid={mid} a[mid]={a[mid]} -> {'lo' if go_right else 'hi'}")
        if go_right:
            lo = mid + 1
        else:
            hi = mid
    return lo


print(lower_bound_trace([1, 2, 2, 2, 3, 5], 2))   # 1

Why it terminates and why it is correct

In the half-open form, lo <= mid < hi holds whenever lo < hi. Both updates, lo = mid + 1 and hi = mid, shrink the range by at least one, so the loop always ends. The invariant "everything before index lo is less than x, and everything from index hi on is at least x" is preserved, so the moment lo == hi that position is exactly the boundary.

A classic mistake is writing lo = mid. When lo + 1 == hi, mid equals lo, the range never shrinks, and the loop spins forever. Mixing closed and half-open intervals in the same function is the other main source of off-by-one errors, so pick one convention and stick to it.

Searching on the answer: integer square root

Let us compute the integer square root of n = 40, the largest r with r * r <= n. The predicate P(r) = r * r > n flips from false to true exactly once as r grows. Find the first r where it is true and subtract one.

def first_true(lo, hi, pred):
    # first index in [lo, hi) where pred is True, given F..F T..T (hi if none)
    while lo < hi:
        mid = (lo + hi) // 2
        if pred(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo


def isqrt(n):
    return first_true(0, n + 2, lambda r: r * r > n) - 1


print(isqrt(40), isqrt(0), isqrt(1), isqrt(49))   # 6 0 1 7

For n = 40, mid takes the values 21, 10, 5, 8, 7, 6, and the search stops at the empty range [7, 7) returning 7, so the answer is 6. The upper limit is n + 2 because (n + 1) ** 2 > n always holds, which guarantees the first true value lies inside the range.

Ternary search

To find the maximum of a unimodal function f on a real interval [lo, hi], compare two points m1 = lo + (hi - lo) / 3 and m2 = hi - (hi - lo) / 3. If f(m1) < f(m2), the maximum lies to the right of m1, so set lo = m1; otherwise set hi = m2. Each round keeps two thirds of the interval.

def ternary_max(f, lo, hi, iterations=100):
    for _ in range(iterations):
        m1 = lo + (hi - lo) / 3
        m2 = hi - (hi - lo) / 3
        if f(m1) < f(m2):
            lo = m1
        else:
            hi = m2
    return (lo + hi) / 2


print(round(ternary_max(lambda x: -(x - 2) ** 2 + 5, 0, 10), 6))   # 2.0

On integers, a binary search on the predicate f(m) < f(m + 1) is simpler and needs fewer evaluations. Note that flat stretches where neighboring values are equal break the monotonicity both methods rely on, and either one can then return a wrong position.

Summary

  • Binary search halves the range at each step and stops when the range is empty or lo meets hi.
  • With the half-open interval [lo, hi) and only the updates lo = mid + 1 and hi = mid, infinite loops and off-by-one errors are easy to avoid.
  • One helper, first_true, covers lower_bound, integer square roots, and optimization problems alike.
  • Ternary search finds the extremum of a unimodal function; on integers, a neighbor-comparison binary search does the same job.

0 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.