Professional Documents
Culture Documents
QUESTION # 01:
Assume array[]= {2,4,6,8,}. Give implementation of linear search algorithm to;
i. find element 8 in array
ii. find element 3 in array
int main()
{
int DATA[4] = { 2, 4, 6, 8, };
cout << "Location of 8 is " << linearSearch(DATA, 4, 8) << endl;
cout << "Location of 3 is " << linearSearch(DATA, 4, 3) << endl;
return 0;
}
Output:
QUESTION # 02:
let assume A[]= {2,5,5,5,6,6,8,9,9,9} sorted array of integers containing duplicates, apply binary
search algorithm to Count occurrences of a number provided, if the number is not found in the
array report that as well. (Give implementation)
1
Source Code (C++):
# include <iostream>
using namespace std;
return count;
}
}
int main()
{
int DATA[]= { 2, 5, 5, 5, 6, 6, 8, 9, 9, 9, };
int LB = 0, UB = 9;
int ITEM = 5;
int count = countOccurances(DATA, LB, UB, ITEM);
cout << "Count of " << ITEM << " is " << count << endl;
return 0;
}
2
Output:
QUESTION # 03:
Compare linear & binary Search algorithms on the basis of time complexity , which one is better
in your opinion? Discuss.
O(n) O(log n)
The linear search algorithm finds an The binary search algorithm finds an
General Time item by comparing it with the items in item by keeping on dividing the array
Complexity an array in a linear fashion (from left into half repeatedly (or recursively)
to right) until an item matches. and comparing the middle element
with the item to be searched until it
matches.
O(1) O(1)
Best Case If the first item is the item to be If the left middle item is the item to be
Time searched, then only one comparison is searched, then only one comparison is
Complexity made and the algorithm takes constant made and the algorithm takes constant
time. time.
O(n) O(log n)
Worst Case
If the last item is the item to be If either the leftmost or the rightmost
Time
searched, then “n” comparisons are item is the item to be searched then
Complexity
made “⌊logn⌋” comparisons are made.
Conclusion:
Since under different conditions, the algorithms have their own benefits therefore, it cannot be
decided that which one of them is better to use. Hence, we consider both of the algorithms as the
best of their kind.