Binary Search

algorithms

Binary Search

Binary Search is an efficient searching algorithm used to find a target value inside a sorted array. Instead of checking every element one by one like Linear Search, Binary Search repeatedly divides the search space in half until the target is found or the search range becomes empty.

Because it cuts the search area in half each step, Binary Search is much faster on large datasets.

How Binary Search Works

The algorithm follows these steps:

  1. Find the middle element of the array.
  2. Compare the middle element with the target value.
  3. If the target matches the middle element, return the index.
  4. If the target is smaller, continue searching the left half.
  5. If the target is larger, continue searching the right half.
  6. Repeat until the value is found or no elements remain.

Example Array

const numbers = [1, 3, 5, 7, 9, 11, 13, 15];

If we want to search for 11:

  • Start in the middle (7)
  • 11 is greater than 7
  • Search the right half
  • Middle becomes 11
  • Value found

Binary Search in JavaScript

function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const middle = Math.floor((left + right) / 2);

    if (arr[middle] === target) {
      return middle;
    }

    if (arr[middle] < target) {
      left = middle + 1;
    } else {
      right = middle - 1;
    }
  }

  return -1;
}

const numbers = [1, 3, 5, 7, 9, 11, 13, 15];

console.log(binarySearch(numbers, 11)); // 5

Time Complexity

OperationComplexity
Best CaseO(1)
Average CaseO(log n)
Worst CaseO(log n)

Binary Search is significantly faster than Linear Search for large sorted datasets.

Space Complexity

ImplementationComplexity
IterativeO(1)
RecursiveO(log n)

Binary Search is useful when:

  • The data is already sorted
  • Fast lookups are needed
  • Working with large datasets
  • Searching IDs, usernames, timestamps, or ordered values

Common Mistake

Binary Search only works correctly on sorted arrays.

This will produce incorrect results:

const numbers = [9, 1, 15, 3, 7];

Always sort the array first before using Binary Search.

Recursive Version

function recursiveBinarySearch(arr, target, left = 0, right = arr.length - 1) {
  if (left > right) {
    return -1;
  }

  const middle = Math.floor((left + right) / 2);

  if (arr[middle] === target) {
    return middle;
  }

  if (arr[middle] < target) {
    return recursiveBinarySearch(arr, target, middle + 1, right);
  }

  return recursiveBinarySearch(arr, target, left, middle - 1);
}

Final Thoughts

Binary Search is one of the most important algorithms in computer science and technical interviews. Understanding how it works helps build stronger problem-solving skills and introduces the concept of divide-and-conquer algorithms.

Once you understand Binary Search, it becomes easier to learn more advanced searching and tree-based algorithms.

Case Study

In Progress

Bible Verse — Case Study

Production SaaS Platform · Full-Stack · Founder & Sole Engineer

A domain-driven SaaS platform with five independently scalable system boundaries: scripture content delivery, RAG-backed AI study, real-time community interaction, async media processing, and infrastructure services — built and operated end-to-end.

Our Results

37K+
Verses Indexed
5
AI Models
5
Bounded Domains
3
Job Queues

How We Built It

  • RAG pipeline grounding AI responses in actual scripture rather than model memory
  • Hybrid Llama / OpenAI routing — local inference for cost, API fallback for quality at the edge
  • Non-blocking media processing — FFmpeg jobs enqueued via BullMQ, API never waits on transcoding
  • Cross-instance real-time consistency via Redis pub/sub behind WebSocket and WebRTC layers

Lessons Learned

  • Domain boundaries enforced at the service layer prevent coupling long before scale demands microservices.
  • RAG retrieval quality matters more than model size — better embeddings outperform a larger model on poor context.
  • Async queue design should be first-class, not bolted on; BullMQ worker isolation saved the request path repeatedly.

Stack

Nuxt 3TypeScriptNitroPostgreSQLPrismaRedisBullMQWeaviateMinIOFFmpegWebRTCWebSocketsLlama 3.2OpenAI APIKubernetes
View Full Case Study

Written by

Full-Stack Engineer & Systems Architect

5+ years building production systems · AI, Backend & Infrastructure · Founder of Bible Logic

Full-stack engineer with 5+ years of hands-on experience designing and shipping production systems — from Nuxt 3 frontends and Nitro APIs to self-hosted Kubernetes clusters, RAG pipelines, and real-time AI applications. Everything I write comes from systems I've designed, deployed, and operated in production.

5+ Years Experience AI Systems Specialist Kubernetes & Infrastructure
Nuxt 3TypeScriptPostgreSQLKubernetesRAG / LLMWebRTCAWS IVSRedis