Searching

Searching is a process of finding the correct location of an element from a list or array of elements. In an array, elements are stored in consecutive memory locations with the remaining element until the exact match is found. If the element is found, the search process is said to be successful or else the search process is terminated unsuccessfully.

Binary Search

The sequential search situation will be in worst case if the element is at the end of the list. For eliminating this problem, we have one efficient searching technique called binary search. The condition for binary search is that all the data should be in a sorted array. We compare the element with the middle element of the array. If it is less than the middle element then search it in the left position of the array and if it is greater than the middle element then the search will be in the right portion of the array. We will take that portion only for search and compare with the middle element of that portion. This process will be in iteration until we find the element or middle element has no left or right portion to search.

Binary Search algorithm implementation in c

#include<stdio.h>
#include<alloc.h>

int main()
{
  int*arr,size,data;
  int min,max,mid,position,i;
  printf("ENTER ARR SIZE: ");
  scanf("%d",&size);

  arr=(int*)calloc(size,sizeof(int));
  printf("\nENTER %d values: ",size);
  for(i=0;i<size;i++)
   scanf("%d",&arr[i]);
 printf("\nENTER DATA TO BE SEARCH:");
 scanf("%d",&data);
 min=0;
 max=size-1;
 for(min=0;min<=max; min++)
 {
   if(arr[min]==data)
   {
     position=min+1;
     break;
   }
   mid=(min+max)/2;
   if(arr[mid]<=data)
   {
     if(arr[mid]==data)
     {
   position=mid+1;
   break;
     }
     min=mid;
   }
   else
   {
      max=mid-1;
      min=0;
   }
  }
  if(min>max)
    printf("\nDATA IS NOT FOUND");
  else
   printf("%d is at %d position",data,position);
  free(arr);
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *