C Program search an element using binary search


This program is to search an element in an array using binary search method. Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer.

Binary search search a particular item by comparing the middle item of the collection. If match occurs then index of item is returned.

If middle item is greater than item then item is searched in sub-array to the right of the middle item other wise item is search in sub-array to the left of the middle item.
This process continues on sub-array as well until the size of sub-array reduces to zero.


ALGORITHM:-


Step 1: First Enter the size of array
Step 2: insert the element in array
Step 3: Enter the element to be search in array
Step 4: Find the middle most element by divide/2 of collections if items
Step 5: if(middle > search item) then search in right side
Step 6: if(middle < search item) then search in left side
Step 7: if item is found print 'item is found' else 'not found'
Step 8: Stop the execution

C Program search an element using binary search


PROGRAM CODE:-

#include<stdio.h>
#include<conio.h>
void main() {
        int arr[30],i,n,first,last,middle,search;
        clrscr();
        printf("Enter lenght of array: ");
        scanf("%d",&n);
        for(i = 0;i < n; i++)
        {
                printf("value at arr[%d]",i);
                scanf("%d", &arr[i]);
        }
        printf("Enter element to be search in array: ");
        scan("%d", &search);
        first = 0;
        last = n-1;
        while(first < =last)
        {
                middle = (first+last)/2;
                if(arr[middle] < search)
                {
                        first = middle+1;
                }
                else if(arr[middle]==search)
                {
                        printf("Element %d is found at arr[%d]",search,middle);
                        break;
                }
                else
                {
                        last = middle-1;
                }
        }
        if(first > last)
        {
                printf("Element not found");
        }
        getch();
}


OUTPUT:-

Enter length of array: 4
Enter value at a[0]: 12
Enter value at a[1]: 5
Enter value at a[2]: 20
Enter value at a[3]: 12
Enter element to be search in array: 5

Element 5 is found at a[1]
C Program to search an element in array using binary search
C Program to search an element in array using binary search algorithm
C program to implement the binary search method binary search using c
How to search an element using binary search