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 · 3/6

Implementation

Por ahora, este capítulo solo está disponible en inglés.

This chapter builds the basic component of searching, lower_bound, as a clean Python function and explains it line by line. Then the same routine is ported to C++, Java and TypeScript, together with the standard functions each language already ships and the overflow trap in computing the middle index.

Python implementation

def lower_bound(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo


def upper_bound(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] <= x:
            lo = mid + 1
        else:
            hi = mid
    return lo


def contains(a, x):
    i = lower_bound(a, x)
    return i < len(a) and a[i] == x

Line by line:

  • lo=0, hi=None: the half-open search range [lo, hi). It defaults to the whole array, and like the bisect module the caller can restrict it to a slice.
  • while lo < hi: loop while at least one candidate remains. Once lo == hi, that position is the answer.
  • mid = (lo + hi) // 2: the middle index. Python integers are unbounded, so the sum cannot overflow.
  • if a[mid] < x: lo = mid + 1: if the middle value is smaller than x, neither mid nor anything left of it can be the answer, so discard them.
  • else: hi = mid: if the middle value is at least x, mid itself might be the answer, so keep it and discard only the right side.
  • return lo: at the end, lo is the first index with a[i] >= x, or len(a) when no such element exists.

upper_bound differs in a single comparison (< becomes <=). contains checks that the lower_bound position is inside the array and holds exactly x. The bounds check must come first, otherwise an IndexError is possible.

Checking against the standard library

When you write your own version, randomized comparison against a trusted implementation is the most reliable test.

import random
from bisect import bisect_left, bisect_right

for _ in range(10_000):
    a = sorted(random.randint(0, 20) for _ in range(random.randint(0, 15)))
    x = random.randint(-1, 21)
    assert lower_bound(a, x) == bisect_left(a, x)
    assert upper_bound(a, x) == bisect_right(a, x)
    assert contains(a, x) == (x in a)
print("ok")

Edge cases such as empty arrays, targets below or above every element, and arrays of identical values show up naturally in random inputs. Since Python 3.10 you can also pass a , as in .

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorHow It WorksCapítulo siguienteComplexity
key
bisect_left(records, 30, key=lambda r: r.age)

C++

#include <cstddef>
#include <vector>

std::size_t lower_bound_index(const std::vector<int>& a, int x) {
    std::size_t lo = 0, hi = a.size();
    while (lo < hi) {
        std::size_t mid = lo + (hi - lo) / 2;
        if (a[mid] < x) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

The C++ standard library already has std::lower_bound(a.begin(), a.end(), x), which returns an iterator; subtract a.begin() to get an index. There is also std::upper_bound, std::equal_range for both boundaries at once, and std::partition_point for the boundary of an arbitrary predicate.

Java

public final class Search {
    public static int lowerBound(int[] a, int x) {
        int lo = 0, hi = a.length;
        while (lo < hi) {
            int mid = (lo + hi) >>> 1;
            if (a[mid] < x) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}

Java's Arrays.binarySearch returns the index when the key is found and -(insertion point) - 1 when it is not. With duplicates it makes no promise about which occurrence it returns, so when you need the first one, a hand-written lower_bound like the one above is the safer choice.

TypeScript

export function lowerBound(a: readonly number[], x: number): number {
  let lo = 0;
  let hi = a.length;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (a[mid] < x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

console.log(lowerBound([1, 2, 2, 2, 3, 5], 2)); // 1

JavaScript has no standard binary search for arrays, so you will often write one like this. Numbers are 64-bit floats, so lo + hi cannot overflow, but (lo + hi) >> 1 converts to a signed 32-bit integer and can go wrong for very large values. For arrays of strings or objects, generalize the function to take a comparator.

The middle index and overflow

In languages with fixed-size integers such as C, C++ and Java, (lo + hi) / 2 can overflow when lo and hi are both large. Java's own Arrays.binarySearch carried exactly this bug for years until it was fixed in 2006. There are two safe options:

  • lo + (hi - lo) / 2: add half of the difference, which never exceeds hi.
  • Java's (lo + hi) >>> 1: an unsigned right shift yields the correct value even if the sum wraps negative (as long as lo and hi are non-negative).

Summary

  • Use lower_bound over a half-open interval, with only the updates lo = mid + 1 and hi = mid, as your basic building block.
  • upper_bound changes one comparison; membership is checked from the lower_bound result.
  • Every language ships a standard version (bisect, std::lower_bound, Arrays.binarySearch); check its return convention before relying on it.
  • In fixed-width integer languages, compute the middle as lo + (hi - lo) / 2 to avoid overflow.

0 comentarios

Comentarios destacadosMás recientes primero

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