Sunday, August 12, 2012

Bubble Sort In C++


#include
#include

void main()
{
int array[100],n,i,j,temp;
clrscr();
cout<<"Enter the length of Array--> ";
cin>>n;
cout<<"Enter "<
for(i=0;i
cin>>array[i];
for(i=0;i
{
for(j=0;j
if(array[j]>array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
cout<<"\nArray is sorted in ascending order.\n";
for(i=0;i
cout<
getch();
}

Saturday, August 11, 2012

Binary Search in C++


#include
#include


void binsearch(int ar[],int size,int ele)
{       int lb=0,ub=size-1,mid;             //lb=>lower bound,ub=>upper bound

     for(;lb
       {
           mid=(lb+ub)/2;

           if(ar[mid]==ele)
             {
                cout<<"\n SEARCH SUCCESSFUL";
                break;
             }

           else
                 if(ar[mid]
                 ub=mid-1;

           else
      if(ar[mid]>ele)
      lb=mid+1;
      }

       if(ub

         cout<<"\n SEARCH UNSUCCESSFUL";

}

void sort(int ar[],int size)               //sorts the array in ascending array using bubble sort
{
 int temp;

 for(int i=0;i
for(int j=0;j
if(ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;

}

}

void display(int ar[],int size)
{
 for(int i=0;i
cout<<'\n'<
}

void input(int ar[],int size)
{
 for(int i=0;i
cin>>ar[i];
}

void main()
{
 clrscr();

 int size;
 cout<<"\n ENTER THE NUMBER OF ELEMENTS REQUIRED IN THE ARRAY :";
 cin>>size;

 int *ar=new int(size);

 cout<<"\n ENTER THE ELEMENTS OF THE ARRAY :\n";

 input(ar,size);         //takes the input from the array

 sort(ar,size);         //sorts the array in the ascending order

 int ele;
 cout<<"\n ENTER THE ELEMENT TO BE FOUND :\n";
 cin>>ele;
 binsearch(ar,size,ele);
 getch();

}

Linear Search Program

#include
#include


void main()
{
 clrscr();
 int a[],n,x,i,flag=0;

 cout<<"How many Elements?";
 cin>>n;
 cout<<"\nEnter Elements of the Array\n";


 for(i=0;i  cin>>a[i];
 cout<<"\nEnter Element to search:";
 cin>>x;


 for(i=0;i {
  if(a[i]==x)
  {
   flag++;
   break;
  }
 }

 if(flag==1)
  cout<<"\nElement is Found at position "< else
  cout<<"\nElement not found";
 getch();
}