In: Computer Science
Discrete Math Problems:
ALGORITHM 2 The Linear Search Algorithm.
procedure linear search(x: integer, a1, a2,…, an: distinct integers)
i := 1
while (i ≤ n and x ≠ ai)
i := i + 1
if i ≤ n then location := i
else location := 0
return location{location is the subscript of the term that equals x, or is 0 if x is not found}
// input to algorithm is n, an integer
j := n;
while( j>= 1 )
{
for i := 1 to j
{
x := x + 1;
}
j := floor ( j/2 );
}
Given:
ALGORITHM 2 The Linear Search Algorithm.
procedure linear search(x: integer, a1, a2,…, an: distinct integers)
i := 1
while (i ≤ n and x ≠ ai)
i := i + 1
if i ≤ n then location := i
else location := 0
return location{location is the subscript of the term that equals x, or is 0 if x is not found}
Linear Search number of steps:
If n = 1, number of steps= 1
If n = 2, number of steps= 2
…
If n=n, number of steps= n
So, f(n)=n.
Again,
// input to algorithm is n, an integer
j := n;
while( j>= 1 )
{
for i := 1 to j
{
x := x + 1;
}
j := floor ( j/2 );
}
So, for n=1 number of steps=1
...
for n=8,
f(n)= 4 (while loop) + (8 + 4 + 2 + 1)(for loop) = 19
…
for n=n,