Code Scrappers


Binary Search Using Iteration - C Program


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

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

                  void main()

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

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

                          scanf("%d",&n);

                          printf("enter the array 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 != 0)
                          {
                                  printf("element %d is found at %dth position\n",key, pos);
                          }

                          else
                          {
                                  printf("element is not found");
                          }
                  }

                  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 number of elements
        5

        Enter 5 elements
        1
        25
        56
        87
        92

        Enter the key element
        87

        Element 87 found at 4 position