Anil2447 0 Newbie Poster

Here is the codes for Binary Search and Linear Search.


Binary Search

#include<stdio.h>
int main(){
  int a[10],i,n,m,c=0,l,u,mid,j,x;   //variable assigning
  printf("Enter the size of an array->"); //Entering the size of the array
  scanf("%d",&n);
  printf("\nEnter the elements of the array->");//Entering the array elements
  for(i=0;i<n;i++){
      scanf("%d",&a[i]);
  }
  for(i=0;i<n;i++) {  //loop to sort the elements 
	for(j=i+1;j<n;j++) {
		if(a[i]>a[j]) {
			x=a[i];
			a[i]=a[j];
			a[j]=x;
			
	}
}
}
  printf("\nThe elements of an array are->");//printing the sorted elements
  for(i=0;i<n;i++){
      printf(" %d",a[i]);
  }
  printf("\nEnter the number to be search->");//Entering the key to be found
  scanf("%d",&m);
  l=0,u=n;
  while(l<=u){   //Here starts the coding for Binary search
      mid=(l+u)/2;
      if(m==a[mid]){
      c=1;
          break;
      }
      else if(m<a[mid]){
      u=mid-1;
      }
      else
      l=mid+1;
  }
  if(c==0)
      printf("\nThe number is not in the list");
  else
      printf("\nThe number is found");
  return 0;
}//End of the program.

:icon_lol:


Linear Search

#include <stdio.h>
main(){
	int i,m,n,c;
	int a[10];
	printf("Enter the size of an array->");//Entering the size of Array
  	scanf("%d",&n);
  	printf("\nEnter the elements of the array->");//Entering the array values
  	for(i=0;i<n;i++){
      	scanf("%d",&a[i]);
	}
	printf("Enter the key: ");//Entering the key
	scanf("%d",&m);
	for(i=0;i<5;i++) {   //Loop that Check Linearly
		if(m==a[i]) {
		    c=1;
		    break;		
		}
		else
			c=0;
		}
		
if(c==1)
printf("Element Found\n");
else
printf("Element Not Found\n");
	
}//End of the program

:icon_razz:

-----------------------------------------------------------------------------------------

If any mistakes found please inform me......
Thank You.
Here is a link which suggest you what is a linear search and binary search. And pseudo code for it.
http://www.youtube.com/watch?v=wNVCJj642n4&list=PL89B61F78B552C1AB&index=5