0% found this document useful (0 votes)
8 views

AEC_LAB_EXP-I

The document describes the implementation and time measurement of the Binary Search algorithm using the Divide and Conquer approach. It outlines the steps for setting up the environment, implementing the algorithm, and measuring the execution time. The provided C program demonstrates a recursive binary search and measures the time taken to find a target element in a sorted array.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

AEC_LAB_EXP-I

The document describes the implementation and time measurement of the Binary Search algorithm using the Divide and Conquer approach. It outlines the steps for setting up the environment, implementing the algorithm, and measuring the execution time. The provided C program demonstrates a recursive binary search and measures the time taken to find a target element in a sorted array.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

EXERCISE-1

1. Develop a program and measure the running time for Binary Search with Divide
and Conquer.

Description of Binary Search

Binary Search is an efficient searchingalgorithmusedto findthepositionofatarget element in a


sorted array. It operates using the Divide and Conquer approach, significantly reducing the
size of the search space at each step.

HowBinarySearchWorks:

1. InitialSetup:
o Definetwopointers:onepointingtothebeginningofthearray(left)andtheother tothe end
(right).
2. DividetheSearchSpace:
o Calculatethemiddleindex:mid=⌊(left+right)/2⌋
o Comparethetargetelementwiththeelementatthemiddleindex.
3. Conquer:
o Ifthemiddleelementmatchesthetarget,thesearchis complete.
o Ifthemiddleelementisgreaterthanthetarget, narrowthesearchtotheleft subarray.
o Ifthemiddleelementissmallerthanthetarget,narrowthesearchtotheright subarray.
4. RepeatUntilFoundorExhausted:
o Continuetheprocess untilthetarget isfoundorthesearchspaceisempty.

TimeComplexity:

 BestCase:O(1)(targetisatthemiddleindexinitially).
 AverageandWorstCase: O(logn)(searchspaceishalvedat everystep).

SpaceComplexity:

 Iterativeimplementation:O(1).
 Recursiveimplementation:O(log n)duetofunctioncallstack.

Measuring the running time of Binary Search involves calculating the time taken by the
algorithmto search for atarget element within a sorted array. The process uses timers to capture
the start and end time of the operation.

StepstoMeasure RunningTime:

1. SetUptheEnvironment:
o Generatealargesortedarraytosimulatereal-worldscenarioswhereBinary
Search is applied.
o Chooseatargetelementforthesearch(canbepresentor absentinthe array).
2. ImplementBinarySearch:
o Useeithertheiterativeorrecursiveapproach.ForaDivideandConquer
demonstration, the recursive implementation is preferred.
3. UseTimers:
o Capturethestarttimebeforeinitiating thebinarysearch.
o Executethebinarysearchfunction.
o Capturetheendtimeimmediatelyafter thefunctioncompletes.
4. ComputeElapsedTime:
o Subtractthe starttimefromthe end time toget thetotaltime taken forthe search.
5. InterprettheResults:
o Reporttheelapsedtimeinsecondsormilliseconds.
o Validatethecorrectnessofthesearchresultbychecking thereturned index.

Algorithm:
Asimplealgorithmto measuretherunning timeofBinarySearchusing theDivideand Conquer
approach.Thealgorithminvolvesgeneratinga
largesortedarray,performingabinarysearchfor a target element, and measuring the time
taken for the search.

AlgorithmSteps:

1. GenerateInputData:
o Createa large sorted arrayofintegers(e.g.,arr).
2. ChooseaTarget Element:
o Selectatargetvaluethatmayor maynotbeinthe array.
3. ImplementBinarySearch:
o WritearecursivebinarysearchfunctionusingtheDivideandConquer approach.
4. MeasureTime:
o Useahigh-resolutiontimer tomeasurethestartandendtimeofthebinarysearch
operation.
5. CalculateElapsedTime:
o Computethedifferencebetweenthestart andendtimestodeterminethetime taken
for the search.

PROGRAM:

#include<stdio.h>
#include<time.h>//Formeasuringexecutiontime
//Functionfor BinarySearch
intbinarySearch(intarr[],intleft,intright,inttarget)
{
if(left<=right) {
int mid=left+(right-left)/2;
//Checkifthetargetisatmid if
(arr[mid] == target)
return mid;
//Ifthetargetissmaller,searchtheleftsubarray if
(arr[mid] > target)
returnbinarySearch(arr,left,mid-1,target);
//Otherwise,searchtherightsubarray
returnbinarySearch(arr,mid+1,right,target);
}
//Targetisnotpresentinthearray
return -1;
}
intmain(){
intarr[]={2,3,4,10,40,50,60,70,80,90};
intn=sizeof(arr)/sizeof(arr[0]); int
target = 10, result;
//Measurethestarttime clock_t
start = clock();

//CallBinarySearch
result=binarySearch(arr, 0,n-1,target);
//Measuretheendtime clock_t
end = clock();
//Calculatetheexecutiontime
doubletime_taken=((double)(end-start))/CLOCKS_PER_SEC;
//Outputtheresult if
(result != -1)
printf("Elementfoundatindex%d\n",result); else
printf("Element not found in the array\n");
printf("Executiontime:%fseconds\n",time_taken); return
0;
}

SampleOutput:

Element found at index 3


Executiontime:0.000002seconds

You might also like