Linear Search vs. Binary Search with Duplicates and Inspection Counts
Implement and compare linear search and binary search algorithms with Nexo on a sorted array with duplicates, measuring each approach's element inspections.
Nexo is optimizing the digital identifier search engine at Código con Criterio and needs to empirically compare how many element inspections a linear search performs versus a binary search when the catalog is sorted in ascending order and may contain duplicate values.
Implement the functions busquedaLineal(numeros, objetivo), busquedaBinaria(numeros, objetivo), and solve(input), which receives:
numeros: array of 0 to 1000 integers between -100000 and 100000, sorted in ascending order (duplicates allowed).
objetivo: integer between -100000 and 100000.
busquedaLineal(numeros, objetivo) Requirements
Iterate through numeros with a for loop from index 0 to the end.
At each visited position, increment comparaciones by 1.
If numeros[i] === objetivo, stop immediately and return { indice: i, comparaciones }.
Do not use the ascending order to exit early when numeros[i] > objetivo. If not found, return { indice: -1, comparaciones: numeros.length }.
busquedaBinaria(numeros, objetivo) Requirements
Use a while (izquierda <= derecha) loop with izquierda = 0, derecha = numeros.length - 1, and medio = Math.floor((izquierda + derecha) / 2).
In each iteration, inspect numeros[medio] and increment comparacionesexactly once per iteration.
If numeros[medio] === objetivo, store medio as the candidate index and continue searching in the left half (derecha = medio - 1) to guarantee finding the first occurrence when duplicates exist.
If numeros[medio] < objetivo, update izquierda = medio + 1; if greater, update derecha = medio - 1.
When the loop ends, return { indice, comparaciones } (where indice is the first occurrence or -1).
Coordination in solve(input)
Call both algorithms independently on input.numeros and input.objetivo (without modifying the input) and return an object with exactly six properties:
encontrado: boolean (true if indice !== -1, false otherwise).
indice: integer with the index of the first occurrence or -1.
comparacionesLineal: integer with the inspections performed by busquedaLineal.
comparacionesBinaria: integer with the inspections performed by busquedaBinaria.
algoritmoMasEficiente: "LINEAL" if comparacionesLineal < comparacionesBinaria, "BINARIA" if comparacionesBinaria < comparacionesLineal, or "EMPATE" if equal.
comparacionesAhorradas: integer with Math.abs(comparacionesLineal - comparacionesBinaria).