Code Scrappers


Binary Search C Program Using Recurrsion


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

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

                    void main()

                    {
                            int i, j, n, pos, first, last, a[10], key;

                            printf("enter the size of array\n");

                            scanf("%d",&n);

                            printf("enter the array\n");

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

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

                            scanf("%d",&key);

                            first = 0;

                            last = n-1;

                            pos = binary(a, first, last, key);

                            if(pos)
                            {
                                    printf("\nelement %d is found at %dth position",key, pos);
                            }

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

                            }


                    }
                    int binary(int a[], int first, int last, int key)

                    {
                            int mid;

                            mid = (first + last)/2;

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

                                    else if(key < a[mid])
                                    {
                                            return binary(a, first, mid-1, key);
                                    }

                                    else
                                    {
                                            return binary(a, mid+1, last, key);
                                    }
                            }

                            if(first > last)
                            {
                                  return 0;
                            }
                    }

                



Output

          Enter the number of elements
          5

          Enter 5 elements
          1
          25
          56
          87
          96

          Enter the key element
          87

          Element 87 found at 4 position