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

Week12_handout1

Handout

Uploaded by

info.bptrades
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)
6 views

Week12_handout1

Handout

Uploaded by

info.bptrades
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

CMPT130 J.

Ye Week 12 Handout 1

Linear Search Algorithms Analysis

Given the following two implementations of linear search and three input cases, which
(implementation + input case) takes the least amount of time to complete? The most?

Algorithm/Implementation A:

bool linear_search(int arr[], int size, int target)


{
bool found = false;
int i = 0;
while (i < size)
{
if (arr[i] == target)
found = true;
++i;
}
return found;
}

Algorithm/Implementation B:

bool linear_search(int arr[], int size, int target)


{
bool found = false;
int i = 0;
while (!found && i < size)
{
if (arr[i] == target)
found = true;
++i;
}
return found;
}

Three input cases:

int arr[15] = {2, 56, 8, 5, 11, 92, 77, 36, 9, 102, 20, 25, 150, 44, 50};

1) search 36 in arr

2) search 2 in arr

3) search 23 in arr

1
CMPT130 J. Ye Week 12 Handout 1

To examine which algorithm is more efficient, let’s pick a critical operation which is the comparison
operation arr[i] == target and count how many times this operation will be executed for each
input case in each algorithm. What is your answer?

(For testing purpose, I included an extra variable count and used it to keep track of the number of
comparison operation being executed in the two functions. Then the question becomes: what is the
output?)

Algorithm/Implementation A: bool linear_search(int arr[], int size, int target)


{
bool found = false;

int count = 0;

int i = 0;
while (i < size)
{
if (++count > 0 && arr[i] == target)
found = true;
++i;
}

cout << "count is " << count << endl;

return found;
}

Algorithm/Implementation B:
bool linear_search(int arr[], int size, int target)
{
bool found = false;

int count = 0;

int i = 0;
while (!found && i < size)
{
if (++count > 0 && arr[i] == target)
found = true;
++i;
}

cout << "count is " << count << endl;

return found;
}

You might also like