Given a singly linked list and a key, find key using binary search approach.
To perform a Binary search based on Divide and Conquer Algorithm, determination of the middle element is important. Binary Search is usually fast and efficient for arrays because accessing the middle index between two given indices is easy and fast(Time Complexity O(1)). But memory allocation for the singly linked list is dynamic and non-contiguous, which makes finding the middle element difficult. One approach could be of using skip list, one could be traversing the linked list using one pointer.
Prerequisite : Finding middle of a linked list.
Note: The approach and implementation provided below are to show how Binary Search can be implemented on a linked list. The implementation takes O(n) time.
- Here, start node(set to Head of list), and the last node(set to NULL initially) are given.
- Middle is calculated using two pointers approach.
- If middle’s data matches the required value of search, return it.
- Else if midele’s data < value, move to upper half(setting last to midele's next).
- Else go to lower half(setting last to middle).
- The condition to come out is, either element found or entire list is traversed. When entire list is traversed, last points to start i.e. last -> next == start.
In main function, function InsertAtHead inserts value at the beginning of linked list. Inserting such values(for sake of simplicity) so that the list created is sorted.
Input : Enter value to search : 7 Output : Found Input : Enter value to search : 12 Output : Not Found
Time Complexity : O(n)
- Linked List | Set 1 (Introduction)
- Linked List vs Array
- Find the middle of a given linked list in C and Java
- Linked List | Set 2 (Inserting a node)
- Binary Search
- Practice questions for Linked List and Recursion
- Linked List | Set 3 (Deleting a node)
- Program for n’th node from the end of a Linked List
- Reverse a linked list
- Search an element in a sorted and rotated array
- Doubly Linked List | Set 1 (Introduction and Insertion)
- Circular Linked List | Set 1 (Introduction and Applications)
- Interpolation search vs Binary search
- Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
- Write a function to delete a Linked List
Improved By : sunny94