Binary Search Pseudocode


0

Binary Search is an efficient algorithm to find a target value within a sorted array. The idea is to repeatedly divide the search interval in half.

Pseudocode:

Binary_Search(arr, target)
1. Set low = 0, high = length(arr) - 1
2. While low ≤ high:
     a. mid = (low + high) / 2
     b. If arr[mid] == target:
           Return mid  (found the target at index mid)
     c. Else if arr[mid] < target:
           Set low = mid + 1  (search in the right half)
     d. Else:
           Set high = mid - 1  (search in the left half)
3. If not found, return -1

Explanation:

  • We begin by setting two pointers: low and high.
  • We calculate the middle of the array (mid).
  • If the middle element matches the target, we return its position.
  • Otherwise, if the middle element is less than the target, we adjust the low pointer to narrow down the search to the right half.
  • If the middle element is greater than the target, we adjust the high pointer to focus on the left half.
  • The loop continues until either the element is found or the search space is exhausted.

Like it? Share with your friends!

0
mrwixxsid

0 Comments

Choose A Format
Personality quiz
Series of questions that intends to reveal something about the personality
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Countdown
The Classic Internet Countdowns
Open List
Submit your own item and vote up for the best submission
Ranked List
Upvote or downvote to decide the best list item
Meme
Upload your own images to make custom memes
Video
Youtube and Vimeo Embeds
Audio
Soundcloud or Mixcloud Embeds
Image
Photo or GIF
Gif
GIF format