0% found this document useful (0 votes)
9 views

Binary Search

its

Uploaded by

islamriyadul249
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Binary Search

its

Uploaded by

islamriyadul249
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Binary Search

Introduction: Binary search is an efficient algorithm for finding a target element in a sorted array or list. Unlike linear
search, which checks each element one by one, binary search divides the search range in half each time, significantly
reducing the number of comparisons. It works by comparing the target value to the middle element of the array.

#include <iostream>

using namespace std;

int binarySearch(int arr[], int size, int target) {

int left = 0, right = size - 1;

while (left <= right) {

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

if (arr[mid] == target) {

return mid;

if (arr[mid] > target) {

right = mid - 1;

else {

left = mid + 1;

return -1;

int main() {

int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};

int size = sizeof(arr) / sizeof(arr[0]);

int target;

cout << "Enter the element to search for: ";

cin >> target;

int result = binarySearch(arr, size, target);

if (result != -1) {

cout << "Element " << target << " found at index " << result << endl;

} else {

cout << "Element " << target << " not found." << endl;

return 0;

You might also like