Social Icons

twitterfacebookgoogle pluslinkedinemail

Monday 2 September 2013

Binary sorting in C langaugae

The basic algorithm is this:
  1. Select an arbitrary element and add it to our sorted list, S.
  2. Select another arbirtrary element, x, and, using binary search, try to find x in S.
  3. Place x in S according to the results of the binary search.
  4. Repeat steps 2 and 3 until there are no more elements to select.
C program for binary search: This code implements binary search in c language. It can only be used for sorted arrays, but it's fast as compared to linear search. If you wish to use binary search on an array which is not sorted then you must sort it using some sorting technique say merge sort and then use binary search algorithm to find the desired element in the list. If the element to be searched is found then its position is printed.




#include<iostream.h>
#include<conio.h>
void main()
{
int a[5],i,j,start,end,middle,search,flag=0,loc;
clrscr();
for(i=0;i<5;i++)
cin>>a[i];
cout<<"\nYour array is...";
for(i=0;i<5;i++)
cout<<a[i]<<"\n";
start=0;
end=4;
cout<<"\nEnter element for search..";
cin>>search;
for(i=0;i<5;i++)
{
middle=(start+end)/2;
if(a[middle]==search)
{
cout<<"\nsuccessfull";
loc=middle;
flag=1;
break;
      }
      else if(search>a[middle])
      {
  start=middle+1;
      }
      else
      {
    end=middle-1;
      }
}
if(flag==1)
{
cout<<"\n"<<search<<" is at "<<loc<<" th location...";
}
else
cout<<"\nElement is not found..";
getch();
}









No comments :

Post a Comment

 

Free Advertisement

Free Advertisement

Free Advertisement

Free Advertisement