Week12_handout1
Week12_handout1
Ye Week 12 Handout 1
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:
Algorithm/Implementation B:
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?)
int count = 0;
int i = 0;
while (i < size)
{
if (++count > 0 && arr[i] == target)
found = true;
++i;
}
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;
}
return found;
}