You are on page 1of 4

Experiment 1.

2
NAME- PRAVESH AZAN UID- 19BCS2979

BRANCH- CSE CLASS AND GROUP- A

SEMESTER- 3rd DATE OF PERFORMANCE-


19/06/23
SUBJECT- DATA STRUCTURES
SUBJECT CODE- CSP231

AIM OF THE EXPERIMENT:

AIM: WRITE A PROGRAM TO DEMONSTRATE THE USE OF LINEAR AND BINARY SEARCH TO FIND A GIVEN
ELEMENT IN AN ARRAY.

ALGORITHM –

Binary Search

1. Compare x with the middle element.


2. If x matches with the middle element, we return the mid index.
3. Else if x is greater than the mid element, then x can only lie in the right half
Subarray after the mid element. So, we recur for the right half.

4. Else (x is smaller) recur for the left half.

Linear Search

Start from the leftmost elements of arr[] and one by one compare x with each element of arr[]

If x matches with an element, return the index.

If x does not match with any of the elements, return -1.

PROGRAM CODE:

#include <iostream>

using namespace std;

int linarSearch(int arr[], int N, int x)

int i;

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


if (arr[i] == x)

return i;

return -1;

int binarySearch(int arr[], int l, int r, int x)

while (l<=r) {

int m=l + (r-l)/2;

if (arr[m] == x)

return m;

if(arr[m]<x)

l = m + 1;

else

r = m - 1;

return -1;

int main(void)

{ int n;

cout<<"Enter the number of elements of array:\n";

cin>>n;

int arr[n];

cout<<"Enter the elements of array:\n";

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

cin>>arr[i];

int key;
cout<<"enter the key you want to search in array:\n";

cin>>key;

cout<<"searchng through binary search is:\n"<<endl;

int resultb = binarySearch(arr,0,n - 1,key);

(resultb == -1)

? cout <<"Element is not present in array"<<endl

: cout << "Element is present at index " << resultb << " and at position "<<resultb+1<<endl;

cout<<"Searching through linear Search is"<<endl;

int results = linarSearch(arr,n,key);

(results == -1)

? cout << "Element is not present in array"<<endl

: cout << "Element is present at index " << results << " and at position "<<results+1<<endl;

cout<<"Searching through linear Search is"<<endl;

return 0;

PRORGAM’S EXPLANATION:

The program will ask to search a key element in array with two approaches binary and linear search.
OUTPUT:
LEARNING OUTCOMES (What I have learnt):

1. In this experiment we learn to implement the searching through binary search.


2. In this experiment we learn to implement the searching through linear search.

EVALUATION COLUMN:
Sr. No. Parameters Marks Obtained Maximum Marks
1. Student Performance (Conduct of experiment) 12
Objectives/Outcomes.
2. Viva Voce 10
3. Submission of Work Sheet (Record) 8
Total 30

You might also like