I have a small doubt here…
If I know that a search element in a list ,say containing 32 elements sorted in order, is appearing within first four positions,
which is the best searching algorithm.
Linear search at least needs 4 iteration….
Binary search at least 5 iteration
How about binary search tree .. does it give better solution in this case or is equal to binary search…
I believe Linear search will be better for such circumstances ..
can anybody confirm this please ?
If you know the location is in the first 4 positions than a linear search is better since you’ll have to test no more than 4 elements. With a binary search lg 32 = 5 so you’ll have to test at most 5 elements.
In addition, for a small amount of elements like this, the time difference is negligible and you’ll be best served by keeping it simple and doing a linear search.
You may also be able to use a HashTable or HashSet for O(1) time but then again, for a small amount of data, a linear search would probably be faster than executing a hash function.
And if the small difference really does matter, I would suggest measuring it in the environment where it will run.