You are on page 1of 7

Experiment – 2

Aim: To implement Binary Search and Linear Search algorithms using array as a data
structure and analyse its time complexity.

BINARY SEARCH

Code:
#include <bits/stdc++.h>
#include<iostream>
#include <chrono>
using namespace std;

int midd(int a, int b)


{
int c;
c=(a+b)/2;
return(c);
}

void binarysearch(int arr[], int size, int x)


{
int low,high,mid;
low=0;
high=size-1;
auto start = chrono::steady_clock::now();
while(high>low)
{
mid=midd(high,low);
if(arr[mid]==x)
{
cout<<"The element is found at "
<<mid+1<<"th position";
break;
}
else if(arr[mid]>x)
{
high=mid;
}
else if(arr[mid]<x)
{
low=mid+1;
}
}
if(high==low)
{ if(arr[low]==x)
{
cout<<"The element is found at "<<low<<"th
position";
}
else
{
cout<<"Not found";
}
}

auto end = chrono::steady_clock::now();


cout<<endl<<"Elapsed time in nanoseconds: "<<
chrono::duration_cast<chrono::nanoseconds>(end
- start).count()<< endl;
}
void printArray(int arr[], int size)
{
int i;
cout<<"Sorted Array is : ";
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

int main()
{ cout<<"Enter Array size: ";
int size;
cin>>size;
int arr[100];
cout<<"Enter the array: ";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
printArray(arr, size);
int x;
cout<<"Enter the element to be searched : ";
cin>>x;
binarysearch(arr , size , x);
return 0;
}
Output:
LINEAR SEARCH

Code:
#include <bits/stdc++.h>

#include<iostream>

#include <chrono>

using namespace std;

int midd(int a, int b)

int c;

c=(a+b)/2;

return(c);

void linearsearch(int arr[], int size, int x)

int i;

int c=0;

auto start = chrono::steady_clock::now();\

for(i=0;i<size;i++)

if(arr[i]==x)

cout<<"The element is at position : "<<i+1;

c=1;

break;

}
}

if(c==0)

cout<<"not found";

auto end = chrono::steady_clock::now();

cout<<endl<<"Elapsed time in nanoseconds: "<<

chrono::duration_cast<chrono::nanoseconds>(end - start).count()<< endl;

void printArray(int arr[], int size)

int i;

cout<<"Sorted Array is : ";

for (i = 0; i < size; i++)

cout << arr[i] << " ";

cout << endl;

int main()

{ cout<<"Enter Array size: ";

int size;

cin>>size;

int arr[100];

cout<<"Enter the array: ";

for(int i=0;i<size;i++)

cin>>arr[i];

}
printArray(arr, size);

int x;

cout<<"Enter the element to be searched : ";

cin>>x;

linearsearch(arr , size , x);

return 0;

Output:

You might also like