Binary Search in C++

Binary Search is an algorithm that searches for a specific element in a sorted list by repeatedly dividing the search space in half. It returns the index of the element if it is found, or -1 if it is not found.
mail@pastecode.io avatar
unknown
c_cpp
2 years ago
630 B
1
Indexable
Never
#include <iostream>

int binarySearch(int arr[], int n, int target) {
  int low = 0;
  int high = n - 1;
  while (low <= high) {
    int mid = (low + high) / 2;
    if (arr[mid] == target) {
      return mid;
    } else if (arr[mid] < target) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return -1;
}

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int target = 3;
  int index = binarySearch(arr, 5, target);
  if (index != -1) {
    std::cout << "Element found at index: " << index << std::endl;
  } else {
    std::cout << "Element not found" << std::endl;
  }
  return 0;
}