Code Scrappers


Binary Search C Program


                    #include<stdio.h>
                    #include<stdlib.h>

                    int binary(int[], int, int);

                    int main()

                    {
                            int n, i, a[10], key, pos = 0;

                            printf("enter the no. of elements \n");

                            scanf("%d",&n);

                            printf("enter the elements in ascending order\n");

                            for(i=0;i<n;i++)
                            {
                                    scanf("%d",&a[i]);
                            }

                            printf("enter the element to be searched \n");

                            scanf("%d",&key);

                            pos = binary(a, n, key);

                            if(pos) //pos != 0
                            {
                                    printf("\n%d is found at %dth position\n",key, pos);
                            }

                            else
                            {
                                    printf("\nelement is not found");
                            }

                            return 0;
                    }

                    int binary(int a[], int n, int key)

                    {
                            int first, last, mid;

                            first = 0;
                            last = n-1;

                            mid = (first + last)/2;

                            while(first <= last)
                            {
                                    if(key < a[mid])
                                    {
                                            last = mid-1;
                                    }

                                    else if(key == a[mid])
                                    {
                                            return mid+1;
                                    }

                                    else
                                    {
                                            first = mid+1;
                                    }

                                    mid = (first + last)/2;
                            }

                            if(first > last)
                            {
                                return 0;

                            }
                    }

                



Output

    enter the no. of elements
    5

    enter the elements in ascending order
    1
    4
    7
    9
    17

    enter the element to be searched
    7

    7 is found at 3th position