0% found this document useful (0 votes)
8 views4 pages

Ds Assign Search 2

Linear and binary search

Uploaded by

sjain87654321
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)
8 views4 pages

Ds Assign Search 2

Linear and binary search

Uploaded by

sjain87654321
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/ 4

SHAURYA JAIN

0801ME231095
IT SECOND YEAR (B-3)

Q23 . Write a program to search the desired element from the given data using linear
search.
#include <stdio.h>
void linearsearch (int arr [] , int size ,int desired )
{
int flag =0;
int index;
for(int i=0; i<size ; i++){
if(arr [i]==desired){
flag=1;
index=i; }
}
if(flag>0) {
printf("\ncthe desired element %d is found at index : %d \n",desired , index); }

else{ printf(“\n the desired element isn't present in the array \n"); }
}
int main(){
int A[] = {1,4, 5,2, 66,32,36,0,7,22,27,9,10};
int size = sizeof(A)/ sizeof(A[0]) ;
int desired ;
printf("enter the element u want to search : ");
scanf("%d",&desired);

linearsearch(A , size , desired);


return 0;
}
SHAURYA JAIN
0801ME231095
IT SECOND YEAR (B-3)

Q24 . Write a program to search the desired element from the given data using binary
search.

#include <stdio.h>

int binarysearch(int arr[], int size, int desired) {


int low = 0;
int high = size - 1;

while (low <= high)


{
int mid = (low + high) / 2;

if (arr[mid] == desired) { return mid; }

if (arr[low] <= arr[high])


{

if (arr[mid] < desired) { low = mid + 1; }


else {high = mid - 1;}

}
else {
if (arr[mid] > desired) {low = mid + 1;}
else{high = mid - 1; }
}
}
return -1;
}

int main() {
int arr[] = {200, 182, 161, 142, 64, 27, 22, 16, 14, 12,4,2,1,0};
int size = sizeof(arr) / sizeof(arr[0]);
int desired;

printf("Enter the number to search: ");


scanf("%d", &desired);

int result = binarysearch(arr, size, desired);


SHAURYA JAIN
0801ME231095
IT SECOND YEAR (B-3)

if (result == -1){ printf("the desired element is not present in the array\n");}

else
{
printf("the desired element %d is present atv the index %d\n", desired,result);}

return 0;
}
SHAURYA JAIN
0801ME231095
IT SECOND YEAR (B-3)

You might also like