1 Dec 2019

  • December 01, 2019
  • Amitraj
Searching

-> Searching is the process of finding some particular element in the list. If the element is present in the list, then the process is called successful and the process returns the location of that element, otherwise the search is called unsuccessful.

There are two popular search methods that are widely used in order to search some item into the list. However, choice of the algorithm depends upon the arrangement of the list.

1. Binary Search
2. Linear Search



Binary Search

-> Binary search is the search technique which works efficiently on the sorted lists. Hence, in order to search an element into some list by using binary search technique, we must ensure that the list is sorted.


-> Binary search follows divide and conquer approach in which, the list is divided into two halves and the item is compared with the middle element of the list. If the match is found then, the location of middle element is returned otherwise, we search into either of the halves depending upon the result produced through the match.



C Program to implement Binary Search

#include<stdio.h>
int main()
{
int a[100],left,right,mid,i,n,s;
printf("Enter n value:");
scanf("%d",&n);
printf("Enter %d numbers in Ascending order:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
left=0;
right=n-1;
mid=(left+right)/2;
printf("Enter a number to search:");
scanf("%d",&s);
while((left<=right)&&a[mid]!=s)
{
if(s>a[mid])
left=mid+1;
else
if(s<a[mid])
right=mid-1;
mid=(left+right)/2;
}
if(a[mid]==s)
  printf("number found..");
   else
    printf("number not found..");
    return 0;

}

OUTPUT:-

1. Enter n value:5
Enter 5 numbers in Ascending order:11 22 33 44 55
Enter a number to search:11

number found..


2. Enter n value:5
Enter 5 numbers in Ascending order:11 22 33 44 55
Enter a number to search:58

number not found..

Translate

Popular Posts