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

Complexity

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

Choosing a search method is not only about the cost of one lookup. You also have to weigh the cost of preparing the data, the cost of updates, memory use, and which kinds of questions the structure can answer at all. This chapter lays out the costs of linear search, binary search, parametric search, ternary search and hash lookup, and turns them into rules for picking one.

Linear search

  • Best case: the first element matches, one comparison, O(1).
  • Average case: with the target equally likely anywhere, about n / 2 comparisons, O(n).
  • Worst case: the target is last or missing, n comparisons, O(n).
  • Space: O(1) extra memory.

It needs no preparation and works on unsorted data. Because it reads contiguous memory in order, which caches love, it often beats binary search in practice for a few dozen elements or fewer.

Binary search

Each comparison halves the range, so the worst case is floor(log2 n) + 1 comparisons: 20 for a million elements, 30 for a billion.

  • Time: best O(1) (the closed-interval form can hit the target at the first midpoint), average and worst O(log n). The lower_bound form always runs close to log n steps.
  • Space: O(1) for the loop version, O(log n) for a recursive version because of the call stack.
  • Precondition: the data must be sorted, and sorting costs O(n log n).

Counting the steps makes the logarithmic growth visible.

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


for n in (10, 1_000, 1_000_000):
    a = list(range(n))
    print(n, lower_bound_count(a, n - 1)[1])   # 3, 10, 20

When does sorting pay off?

With k queries, linear search costs k * n while sort-then-search costs n log n + k log n. Once the number of queries is well above log n, sorting wins. If you will search a dataset once or twice and then throw it away, do not sort it.

Inserting into or deleting from a sorted array means shifting the elements behind the position, which is O(n). When updates are frequent, a balanced binary search tree, a B-tree, or a library such as Python's sortedcontainers keeps both lookups and updates near O(log n).

Parametric and ternary search

If the answer range has size R and evaluating the predicate costs , parametric search costs . A predicate that scans the whole array to test feasibility gives . On real numbers, run iterations for a precision , or simply a fixed count such as 100.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorImplementationCapítulo siguientePractice Problems
C
O(C * log R)
O(n log R)
log2(R / eps)
eps

Ternary search keeps two thirds of the range per round and evaluates the function twice each time. For the same precision it therefore needs more evaluations than binary search. If the problem is on integers and can be rewritten as a neighbor-comparison binary search, prefer that.

import math

R, eps = 1e9, 1e-6
print(math.ceil(math.log2(R / eps)))            # binary: about 50 rounds, 50 evaluations
print(math.ceil(math.log(R / eps, 1.5)) * 2)    # ternary: about 86 rounds, about 172 evaluations

Hash lookup

A hash table finds a key in O(1) on average, but if every key lands in the same bucket the worst case degrades to O(n). It also uses more memory than an array, and since it keeps no order it cannot answer range queries, "next larger value", or "k-th smallest".

import random
import timeit
from bisect import bisect_left

data = sorted(random.sample(range(10_000_000), 100_000))
as_set = set(data)
probe = data[len(data) // 2]

print(timeit.timeit(lambda: probe in data, number=200))     # linear: slowest
print(timeit.timeit(lambda: bisect_left(data, probe), number=200))
print(timeit.timeit(lambda: probe in as_set, number=200))   # hash: fastest

The exact numbers depend on your machine, but with 100,000 elements linear search is typically thousands of times slower than the other two, or worse.

Comparison table

MethodPreparationOne lookupInsert / deleteRange and order queriesExtra memory
Linear searchnoneO(n)O(1) (append)possible, but O(n)O(1)
Sorted array + binary searchO(n log n)O(log n)O(n)O(log n + k)O(1)
Balanced BST / B-treeO(n log n)O(log n)O(log n)O(log n + k)O(n)
Hash tableO(n)O(1) averageO(1) averagenot supportedO(n)

Here k is the number of results that fall inside the range.

Summary

  • Linear search is O(n) but needs no preparation, which suits small data and one-off lookups.
  • Binary search is O(log n); the O(n log n) sorting cost is recovered when there are many queries.
  • Parametric search costs O(predicate cost * log range); ternary search needs more evaluations for the same precision.
  • Use a hash for exact matches; use a sorted array or a tree when you need ranges or order.

0 comentarios

Comentarios destacadosMás recientes primero

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