Archive for the ‘Searching Techniques’ Category

Binary Search

Posted: August 31, 2011 by Mayur More in Searching Techniques, Uncategorized

In computer science, a binary search or half-interval search algorithm finds the position of a specified value (the input “key”) within a sorted array. At each stage, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element’s key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special “Not found” indication is returned.

CODE:

#include<stdio.h>
int main()
{
  int i,size,search,c=0,low,upper,mid;
  printf(“Enter the size of an array->”);
  scanf(“%d”,&size);
  int array[size];
  printf(“\nEnter the elements of the array->”);
  for(i=0;i<size;i++){
      scanf(“%d”,&array[i]);
  }
  printf(“\nThe elements of an array are->”);
  for(i=0;i<size;i++)
{
      printf(” %d”,array[i]);
  }
  printf(“\nEnter the number to be search->”);
  scanf(“%d”,&search);
  low=0,upper=n-1;
  while(low<=upper){
      mid=(low+upper)/2;
      if(search==array[mid])
     {
      c=1;
          break;
      }
      else if(search<array[mid])
     {
      upper=mid-1;
      }
      else
      low=mid+1;
  }
  if(c==0)
      printf(“\nThe number is not in the list”);
  else
      printf(“\nThe number is found”);
 }

EXPLANATON:

Linear Search

Posted: August 30, 2011 by Mayur More in Searching Techniques

Linear search i one of the easiest way of  searching an element in the array.

it checks each and every array element with the element to be found.

CODE:

#include<stdio.h>
int main(){
int a[10],i,n,m,c=0;
printf(“Enter the size of an array”);
scanf(“%d”,&n);
printf(“\nEnter the elements of the array”);
for(i=0;i<=n-1;i++){
scanf(“%d”,&a[i]);
}
printf(“\nThe elements of an array are”);
for(i=0;i<=n-1;i++){
printf(” %d”,a[i]);
}
printf(“\nEnter the number to be search”);
scanf(“%d”,&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
c=1;
break;
}
}
if(c==0)
printf(“\nThe number is not in the list”);
else
printf(“\nThe number is found”);
return 0;
}