Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views2 pages

DS Lab

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

DS Lab

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Practical: 4 Write a program for searching an element from the given list

a) Linear search b) Binary search.


_/08/2025

Write a program for searching an element from the given list


a) Linear search.

#include <stdio.h>
int linear_search(int arr[],int n,int target)
{
for(int i=0;i<n;i++){
if(arr[i]==target){
return i;
}
}
return-1;
}
int main (){
int arr[]={12,45,7,23,9,18,56,36};
int
n=sizeof(arr)/sizeof(arr[0]);
int target,pos;
printf("enter the element to
search:"); scanf("%d",&target);
pos=linear_search(arr,n,target);
if(pos!=-1)
printf("element found at index
%d\n",pos); else
printf("element not found\n");
return 0;
}
Output:

Name:S.D inesh Reddy


En roll:92400110082
b) Binary
search. #include
<stdio.h>
int binary_search(int arr[],int n,int target)
{
int left=0,right=n-1;
while(left<=right)
{
int mid=(left+right)/2;
if (arr[mid]==target)
return mid;
else if (arr[mid<target])
left =mid+1;
else
right=mid-1
;
}
}
int main (){
int arr[]={12,45,7,23,9,18,56,56};
int n=sizeof(arr)/sizeof(arr[0]);
int target,pos;
printf("enter the element to
search:"); scanf("%d",&target);
pos=binary_search(arr,n,target);
if(pos!=-1)
printf("element found at index %d\n",pos);
else
printf("element not found\n");
return 0;
}
Output:

Name:S.D inesh Reddy


En roll:92400110082

You might also like