Sunday 9 August 2015

Selection sort using c++

# include<iostream>
using namespace std;
int main()
{       int n,min,i,j,k,temp;
        cout<<"Enter the size of array";
        cin>>n;
        int a[n];
        cout<<"Enter the elements of array";
        for(i=0;i<n;i++)
       cin>>a[i];
        for(j=0;j<n-1;j++)
            {
                  min=j;
                  for(k=j+1;k<n;k++)
                      {
                           if(a[k]<a[min])
                           min=k;
                      }
      
                  temp=a[min];
                 a[min]=a[j];
                 a[j]=temp;
       
           }
    cout<<"The sorted array by selection sort is";
    for(i=0;i<n;i++)
    cout<<a[i]<<endl;
}

Saturday 8 August 2015

Linear search using c++

#include<iostream>
using namespace std;
int lsearch(int a[],int n,int x)
{       int i;
    for(i=0;i<n;i++)
    {   if(a[i]==x)
        return i;
    }
    return -1;
}
int main()
{
     int n,x,i;
     int a[n];
   
     cout<<"Enter the size of  array";
     cin>>n;
    cout<<"Enter the elements of    array";
    for(i=0;i<n;i++)
    cin>>a[i];
    cout<<"The array you entered  is";
    for(i=0;i<n;i++)
    cout<<a[i]<<endl;
    cout<<"Enter the Element you want to find";
    cin>>x;
     int t=lsearch(a,n,x); 
     if(t==-1)
    cout<<"Element does not exist in the array";
    else
       {cout<<"The element exists    at index";
        cout<<t;
        }
   
}

Binary search code in C++

#include<iostream>
using namespace std;
int bsearch(int a[],int n,int x)
{       int start =0;
        int end= n-1;int mid;
        while(start<=end)
              {  
                  mid =(start+end)/2;
                  if(a[mid]==x) 
                     {
                         cout<<"element found at  index";
                        return mid;
                     }
                else if(x<a[mid])
                end=mid-1;
                else
                start=mid+1;
            }
    return -1;
}
int main()
{
     int n,x,i;
     int a[n];
   
     cout<<"Enter the size of array";
     cin>>n;
    cout<<"Enter the elements of  array in"      
                <<" ascending order";
    for(i=0;i<n;i++)
    cin>>a[i];
    cout<<"The array you entered  is";
    for(i=0;i<n;i++)
    cout<<a[i]<<endl;
    cout<<"Enter the Element you want to find";
    cin>>x;
     int t=bsearch(a,n,x); 
     if(t==-1)
    cout<<"Element does not exist in the array";
    else
       {cout<<"The element exists    at index";
        cout<<t;
        }
   
}