You are on page 1of 4

Given an array

a) If which searching algorithm is better (linear or binary search),


what is the time complexity of finding with your chosen algorithm.

ANS;

Binary search will be applied in this array.

To begin with, we take beg=0 and end=6.

We compute location of the middle element as-

mid

= (beg + end) / 2

= (0 + 6) / 2

=3

Here, a[mid] = a[3] = 51 which matches to the element being searched.

So, our search terminates in success and index 3 is returned.

a)If which searching algorithm is better (linear or binary search),


what is the time complexity of finding with your chosen algorithm.

ANS; Linear search will be applied in this array.


Linear Search algorithm compares element 30 with all the elements of the array one by one.

It continues searching until either the element 30 is found or all the elements are searched.

Now,

It compares element 15 with the 1st element 30.

Since 30 = 30, so required element is found.

Now, it stops the comparison and returns index 0 at which element 30 is present.

a) If which searching algorithm is better (linear or binary search),


what is the time complexity of finding with your chosen algorithm.

ANS;

Binary search will be applied in this array.

To begin with, we take beg=0 and end=6.

We compute location of the middle element as-

mid

= (beg + end) / 2

= (0 + 6) / 2

=3

Since a[mid] = 51< 91, so we take beg = mid + 1 = 3 + 1 = 4 whereas end remains unchanged.

We compute location of the middle element as-

mid

= (beg + end) / 2
= (4 + 6) / 2

=5

Since a[mid] = 88< 91, so we take beg = mid + 1 = 5 + 1 = 6 whereas end remains unchanged.

We compute location of the middle element as-

mid

= (beg + end) / 2

= (6+ 6) / 2

=6

Here, a[mid] = a[6] = 91 which matches to the element being searched.

So, our search terminates in success and index 6 is returned.

a) Discuss the time complexity of Linear search algorithm when target is not found.

ANS;

 In every iteration, compare the target value with the current value of the array.
 If the values match, return the current index of the array.
 If the values do not match, move on to the next array element.
 If no match is found, return -1.

b) Discuss the time complexity of Binary search algorithm when target is not found.

ANS;

 If the target value is equal to the middle element of the array, then return the index of the
middle element.
 If not, then compare the middle element with the target value,
 When a match is found, return the index of the element matched.
 If no match is found, then return -1

You might also like