Friday 18 October 2024

Binary search

 Binary search is an efficient algorithm used to find the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half. If the target value is equal to the middle element, the search is complete. If the target is smaller, the search continues in the lower half, and if the target is larger, it continues in the upper half.


mid=low +(High-low)/2


Compare the target value with the element at mid:

  • If arr[mid] == target, return mid.

  • If arr[mid] < target, search the right half by setting low = mid + 1.

  • If arr[mid] > target, search the left half by setting high = mid - 1.



Binary Search 

#include <stdio.h>

#define SIZE 8  // Define the size of the array


// Binary search function

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

    int low = 0, high = SIZE - 1;  // Use SIZE to determine the range


    while (low <= high) {

        int mid = low + (high - low) / 2;  

        if (arr[mid] == target)

            return mid;  // Target found

        else if (arr[mid] < target)

            low = mid + 1;  // Search in the right half

        else

            high = mid - 1;  // Search in the left half

    }

    return -1;  // Target not found

}


int main() {

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


    int target;  // Variable to store the target value


    // Take input from user

    printf("Enter the target value: ");

    scanf("%d", &target);


    // Perform binary search without passing the size

    int result = binarySearch(arr, target);


    // Display the result

    if (result != -1)

        printf("Element found at index %d\n", result);

    else

        printf("Element not found\n");


    return 0;

}