BINARY SEARCH

Example: The list to be searched: L = 1 3 4 6 8 9 11. The value to be found: X = 4.

   Compare X to 6. It's smaller. Repeat with L = 1 3 4.
   Compare X to 3. It's bigger. Repeat with L = 4.
   Compare X to 4. It's equal. We're done, we found X. 

Algorithm Goes Here –

binaryalgo

Program – 

#include"conio.h"
#include"iostream"
using namespace std;
main()
{
	int *a,mid,beg,end,i,n,s;
	cout<<"\nENTER THE NO. OF TOTAL ELEMENTS : ";
	cin>>n;
	cout<<"\nENTER SORTED ELEMENT IN LIST : ";
	cout<<endl;
	a=new int[n];
	for(i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	cout<<"\nENTER SEARCH TERM : ";
	cin>>s;
	beg=1;
	end=n;
	mid=(beg+end)/2;
	while(beg<=end && a[mid]!=s)
	{
		if(a[mid]<s)
			beg=mid+1;
		else
			end=mid-1;
		mid=(beg+end)/2;
	}
	if(s==a[mid])
		cout<<"\nITEM FOUND "<<s<<" AT LOCATION "<<mid;
	else
		cout<<"\nITEM NOT FOUND";
	cout<<"\n\nPROGRAMMING @ C#ODE STUDIO";
	getch();
	return 0;
}

Output –

Binarysearch

LINEAR SEARCH : STRUCTURE

Linear search is searching logic perform linearly, that means if we have to treverse all the data stored in structure untill we found actual data.

It is complex in memory space and time as well. Next thing we come to know about searching is Binary search.

#include<iostream.h>
#include<conio.h>
using namespace std;

int main()
{
    struct employee
    {
           char *name;
           int id;
           char *add;
    }*e;
    int i;
    int uid;
    e=new struct employee[5];
    for(i=0;i<5;i++)
    {
   	e[i].name=new char[20];
   	e[i].add=new char[20];
    cout<<"\n ENTER DATA FOR "<<i+1<<" EMPLOYEE:\n\n";
    cout<<"\nName: ";
    cin>>e[i].name;
    cout<<"\nIdentity no.: ";
    cin>>e[i].id;
    cout<<"\nADDRESS: ";
    cin>>e[i].add;
    }
    bool flag=true;
    cout<<"\nEnter UID You Want to Search : ";
    cin>>uid;
   	for(i=0;i<5;i++)
     {
                     if(e[i].id==uid)
                     {
                     	      flag=false;
                              cout<<"\n\n\nName="<<e[i].name<<"\nIDENTITY NO.="<<e[i].id<<"\nADDRESS.="<<e[i].add;            
                     }
     }
     if(flag)
     {
     	cout<<"\nSORRY!! DATA NOT FOUND";
     }
     cout<<"\n\nPROGRAMMING @C#ODE STUDIO";
     getch();
}

OUTPUT

Linear_search

2-D ARRAY USING POINTERS

 

In a 2D array we have to allocate memory two times. As we have to take 2 dereferencing pointer to get value from particular address.

Go through program —

#include"conio.h"
#include"iostream"
using namespace std;
int main()
{
	int **a;
	int i,j;
	a=new int*[3]; //ALLOCATION OF ARRAY OF SIZE 3
	for(i=0;i<3;i++)
		a[i]=new int[3]; //ALLOCATION OF ARRAY OF SIZE 3
	for(i=0;i<3;i++)
		for(j=0;j<3;j++)
		{
			cout<<"\nEnter <"<<i<<"><"<<j<<"> :";
			cin>>a[i][j]; 
		}
	for(i=0;i<3;i++)
		for(j=0;j<3;j++)
		{
			cout<<"\nValues <"<<i<<"><"<<j<<"> :";
			cout<<a[i][j]<<endl;
		}
	cout<<"\nPROGRAMMING @ C#ODE STUDIO";
	getch();
	return 0;
}

2d