Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.5 kB
2
Indexable
Never
#include <stdio.h>    // Include the standard input/output library

// Binary Search Function
int binarySearch(int arr[], int left, int right, int target);  // Function declaration

int main()          // Start of the main function
{
    int a[50], i, size, ele;  // Declare integer variables and an array
    
    printf("*****Binary Search******");  // Display a message indicating the start of the binary search program
    
    printf("\nEnter the size of the array: ");  // Prompt the user to enter the size of the array
    scanf("%d", &size);  // Read the size of the array from the user
    
    printf("\nEnter the elements in the sorted array: ");  // Prompt the user to enter the sorted elements of the array
    for (i = 0; i < size; i++)  // Loop to read the elements and store them in the array
    {
        scanf("%d", &a[i]);
    }
    
    printf("\nArray elements are:");  // Display a message indicating the display of array elements
    for (i = 0; i < size; i++)  // Loop to display the elements of the array
    {
        printf("\n %d", a[i]);
    }
    
    printf("\nEnter the element you want to search: ");  // Prompt the user to enter the element to search
    scanf("%d", &ele);  // Read the element to search from the user
    
    int result = binarySearch(a, 0, size - 1, ele);  // Call the binarySearch function to find the index of the target element
    
    if (result != -1)
    {
        printf("Element found at index %d", result);  // Display the index of the found element
    }
    else
    {
        printf("Element not found");  // Display a message indicating the element was not found
    }

    return 0;  // Return 0 to indicate successful program execution
}

// Binary Search Function Definition
int binarySearch(int arr[], int left, int right, int target)  // Function definition
{
    while (left <= right)  // Loop until the left index is less than or equal to the right index
    {
        int mid = left + (right - left) / 2;  // Calculate the middle index
        
        if (arr[mid] == target)  // If the middle element is the target element
            return mid;  // Return the index of the target element
        
        if (arr[mid] < target)  // If the middle element is less than the target element
            left = mid + 1;  // Continue the search in the right half
        else
            right = mid - 1;  // Continue the search in the left half
    }

    return -1;  // Element not found, return -1
}