Items that are not suitable for a binary search?
Answers
Answered by
0
binary search is possible on linked list data structure but there is no point using it, because at the end it would take same time as normal linear search.
Binary search reduces the number of elements to be searched by filtering out almost half the number of elements at each iteration. For the best implementation of Binary search we need two prerequisites:
The list must be in sorted order.
Any random element can be accessed in constant time.
With linked list the second prerequisite is not satisfied as any random element in linked list cannot be accessed in constant time, but it must be traversed completely.
It must be traversed and there is no other way because each element in linked list is not stored contiguously but in random locations and it could be accessed only by traversing the previous element. (The previous element stores the address of the next element)
In an array basically any random element is accessed as,
Address of any random element = Base address of the array + index of the element*size of the element
This also answers the question why to have elements of array of the same datatype.
The above calculation makes it possible to access any element in an array in constant time. So binary search is preferred in array list, but not in linked list.
Binary search reduces the number of elements to be searched by filtering out almost half the number of elements at each iteration. For the best implementation of Binary search we need two prerequisites:
The list must be in sorted order.
Any random element can be accessed in constant time.
With linked list the second prerequisite is not satisfied as any random element in linked list cannot be accessed in constant time, but it must be traversed completely.
It must be traversed and there is no other way because each element in linked list is not stored contiguously but in random locations and it could be accessed only by traversing the previous element. (The previous element stores the address of the next element)
In an array basically any random element is accessed as,
Address of any random element = Base address of the array + index of the element*size of the element
This also answers the question why to have elements of array of the same datatype.
The above calculation makes it possible to access any element in an array in constant time. So binary search is preferred in array list, but not in linked list.
Similar questions