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.
 avatar
unknown
c_cpp
3 years ago
630 B
4
Indexable
#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;
}
Editor is loading...