C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Wednesday, September 6, 2023

Binary Search Program in C Plus Plus

Binary Search Program in C Plus Plus - 

What is Binary Search? 

Binary search is an efficient algorithm used to search for a specific element in a sorted array or list. When the target element is not found, binary search has a well-defined termination condition.

Binary Search Program in C Plus Plus C ++



Binary Search Program in C Plus Plus C ++

#include<iostream> 

using namespace std;

// Binary search function
int binarySearch(int arr[], int size, int target) {
    int beg = 0;
    int end = size - 1;

    while (beg <= end) {
        int mid = beg + (end - beg) / 2; // Calculate the middle index

        if (arr[mid] == target) {
            return mid; // Target found, return the index
        } else if (arr[mid] < target) {
            beg = mid + 1; // Target is in the right half
        } else {
            end = mid - 1; // Target is in the left half
        }
    }

    return -1; // Target not found
}

int main() {
    int arr[] = {10, 55, 56, 78, 90, 91, 100, 200};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
    int target = 56;

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

    if (result != -1) {
        cout << "Target " << target << " found at index " << result << endl;
    } else {
        cout << "Target " << target << " not found in the array." << endl;
    }

    return 0;
}

Output:


Share:

EasyCPPprogramming.blogspotcom

Labels