Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Logo

Contents:

  • Conventions
  • Overview
  • Software
    • Software Manual
  • User Manual
    • Introduction to User Manual
  • Python Programs
  • C++ Programs
    • C++ Intro
  • Bibliography
  • Test Page
  • Binary Search
  • Stack
  • Vim Notes
  • Binary Tree
Back to top
View this page

Binary Search¶

Code for Binary Search Clone¶

#include <iostream>
#include <vector>
#include <algorithm>


void printResult(int targetNum, int resultNum) {
    if (resultNum != -1) {
       std::cout << "Element " << targetNum << " found at index " << resultNum << std::endl;
   } else {
       std::cout << "Element " << targetNum << " not found in the array." << std::endl;
   }
}


// Function to perform binary search
int binarySearch(const std::vector<int>& arr, int target) { // -> function that takes in vector list of numbers and the target number
   int left = 0;
   int right = arr.size() - 1; // -> creating the start and end points of the vector

   int result = -1;

   while (left <= right) {
       int mid = left + (right - left) / 2;

       // Check if the target is present at the middle
       if (arr[mid] == target) {
           result = mid; // Target found, return its index
       }

       // If the target is greater, ignore the left half
       if (arr[mid] < target) {
           left = mid + 1;
       }

       // If the target is smaller, ignore the right half
       else {
           right = mid - 1;
       }
   }

   printResult(target, result);
   return result;

}




int main() {
   std::vector<int> sortedArray = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
   int target = 23;

   int result = binarySearch(sortedArray, target);

   result = binarySearch(sortedArray, 91);
   result = binarySearch(sortedArray, 5);
   result = binarySearch(sortedArray, 2);
   result = binarySearch(sortedArray, 21);

   std::cout << "------" << std::endl;


   std::vector<int> primeList = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
   
   
   result = binarySearch(primeList, 71);
   result = binarySearch(primeList, 2);
   result = binarySearch(primeList, 31);
   result = binarySearch(primeList, 21);
   result = binarySearch(primeList, -3);
   

   return 0;
}
Next
Stack
Previous
Test Page
Copyright © 2025, ajp
Made with Sphinx and @pradyunsg's Furo
On this page
  • Binary Search
    • Code for Binary Search Clone