Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Búsqueda
Búsqueda
Searching ConceptsHow It WorksImplementationComplexityPractice ProblemsSearching in the Real World
Debates

Guía de Búsqueda · 2/6

How It Works

Por ahora, este capítulo solo está disponible en 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.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorSearching ConceptsCapítulo siguienteImplementation
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 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.