Given a sorted singly linked list and a key, the task is to find the key in the Linked List using Binary Search.
Examples:
Input: head = 1->4->7->8->9->10, key = 7 Output: Present
Input: LinkedList = 1->4->7->8->9->10, key = 12 Output: Value Not Present
Note that Binary Search does not work efficiently for linked lists. The purpose of this article is to show the same. It is recommended to use simple linear search. If we wish to achieve better than linear time, Skip List is recommended for fast search.
if the key is found in the middle element, return true.
If the key is not found in the middle element, choose which half will be used as the next search space.
If the key is smaller than the middle node, the left half is used for the next search.
If the key is greater than the middle node, then the right half is used for the next search.
This process is continued until the key is found or the total Linked List is exhausted.
Below is the implementation of the above approach:
C++
// C++ code to implement binary search// on Singly Linked List#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=NULL;}};// function to find out middle elementNode*middle(Node*start,Node*last){if(start==NULL){returnNULL;}if(start==last)returnstart;Node*slow=start;Node*fast=start->next;while(fast!=last){fast=fast->next;slow=slow->next;if(fast!=last){fast=fast->next;}}returnslow;}// Function for implementing the Binary// Search on linked listboolbinarySearch(Node*head,intvalue){Node*start=head;Node*last=NULL;while(true){// Find middleNode*mid=middle(start,last);// If middle is emptyif(mid==NULL){returnfalse;}// If value is present at middleif(mid->data==value)returntrue;// If start and last node are overlappingelseif(start==last)break;// If value is more than midelseif(mid->data<value){start=mid->next;}// If the value is less than mid.elseif(mid->data>value)last=mid;}// value not presentreturnfalse;}intmain(){// Create a hard-coded linked list:// 1 -> 4 -> 7 -> 8 -> 9 -> 10Node*head=newNode(1);head->next=newNode(4);head->next->next=newNode(7);head->next->next->next=newNode(8);head->next->next->next->next=newNode(9);head->next->next->next->next->next=newNode(10);intvalue=7;if(binarySearch(head,value))cout<<"Present";elsecout<<"Value not present\n";return0;}
C
// C code to implement binary search// on Singly Linked List#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// function to find out middle elementstructNode*middle(structNode*start,structNode*last){if(start==NULL){returnNULL;}if(start==last)returnstart;structNode*slow=start;structNode*fast=start->next;while(fast!=last){fast=fast->next;slow=slow->next;if(fast!=last){fast=fast->next;}}returnslow;}// Function for implementing the Binary// Search on linked listintbinarySearch(structNode*head,intvalue){structNode*start=head;structNode*last=NULL;while(1){// Find middlestructNode*mid=middle(start,last);// If middle is emptyif(mid==NULL){return0;}// If value is present at middleif(mid->data==value)return1;// If start and last node are overlappingelseif(start==last)break;// If value is more than midelseif(mid->data<value){start=mid->next;}// If the value is less than mid.elseif(mid->data>value)last=mid;}// value not presentreturn0;}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a hard-coded linked list:// 1 -> 4 -> 7 -> 8 -> 9 -> 10structNode*head=createNode(1);head->next=createNode(4);head->next->next=createNode(7);head->next->next->next=createNode(8);head->next->next->next->next=createNode(9);head->next->next->next->next->next=createNode(10);intvalue=7;if(binarySearch(head,value))printf("Present\n");elseprintf("Value not present\n");return0;}
Java
// Java code to implement binary search// on Singly Linked ListclassNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}publicclassGfG{// function to find out middle elementstaticNodemiddle(Nodestart,Nodelast){if(start==null){returnnull;}if(start==last)returnstart;Nodeslow=start;Nodefast=start.next;while(fast!=last){fast=fast.next;slow=slow.next;if(fast!=last){fast=fast.next;}}returnslow;}// Function for implementing the Binary// Search on linked liststaticbooleanbinarySearch(Nodehead,intvalue){Nodestart=head;Nodelast=null;while(true){// Find middleNodemid=middle(start,last);// If middle is emptyif(mid==null){returnfalse;}// If value is present at middleif(mid.data==value)returntrue;// If start and last node are overlappingelseif(start==last)break;// If value is more than midelseif(mid.data<value){start=mid.next;}// If the value is less than mid.elseif(mid.data>value)last=mid;}// value not presentreturnfalse;}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 4 -> 7 -> 8 -> 9 -> 10Nodehead=newNode(1);head.next=newNode(4);head.next.next=newNode(7);head.next.next.next=newNode(8);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);intvalue=7;if(binarySearch(head,value))System.out.println("Present");elseSystem.out.println("Value not present");}}
Python
# Python code to implement binary search# on Singly Linked ListclassNode:def__init__(self,new_data):self.data=new_dataself.next=None# function to find out middle elementdefmiddle(start,last):ifstartisNone:returnNoneifstart==last:returnstartslow=startfast=start.nextwhilefast!=last:fast=fast.nextslow=slow.nextiffast!=last:fast=fast.nextreturnslow# Function for implementing the Binary# Search on linked listdefbinary_search(head,value):start=headlast=NonewhileTrue:# Find middlemid=middle(start,last)# If middle is emptyifmidisNone:returnFalse# If value is present at middleifmid.data==value:returnTrue# If start and last node are overlappingelifstart==last:break# If value is more than midelifmid.data<value:start=mid.next# If the value is less than mid.elifmid.data>value:last=mid# value not presentreturnFalseif__name__=="__main__":# Create a hard-coded linked list:# 1 -> 4 -> 7 -> 8 -> 9 -> 10head=Node(1)head.next=Node(4)head.next.next=Node(7)head.next.next.next=Node(8)head.next.next.next.next=Node(9)head.next.next.next.next.next=Node(10)value=7ifbinary_search(head,value):print("Present")else:print("Value not present")
C#
// C# code to implement binary search// on Singly Linked ListusingSystem;classNode{publicintData;publicNodenext;publicNode(intx){Data=x;next=null;}}classGfG{// function to find out middle elementstaticNodeMiddle(Nodestart,Nodelast){if(start==null){returnnull;}if(start==last){returnstart;}Nodeslow=start;Nodefast=start.next;while(fast!=last){fast=fast.next;slow=slow.next;if(fast!=last){fast=fast.next;}}returnslow;}// Function for implementing the Binary// Search on linked liststaticboolBinarySearch(Nodehead,intvalue){Nodestart=head;Nodelast=null;while(true){// Find middleNodemid=Middle(start,last);// If middle is emptyif(mid==null){returnfalse;}// If value is present at middleif(mid.Data==value){returntrue;}// If start and last node are overlappingelseif(start==last){break;}// If value is more than midelseif(mid.Data<value){start=mid.next;}// If the value is less than mid.elseif(mid.Data>value){last=mid;}}// value not presentreturnfalse;}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 4 -> 7 -> 8 -> 9 -> 10Nodehead=newNode(1);head.next=newNode(4);head.next.next=newNode(7);head.next.next.next=newNode(8);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);intvalue=7;if(BinarySearch(head,value)){Console.WriteLine("Present");}else{Console.WriteLine("Value not present");}}}
JavaScript
// JavaScript code to implement binary search// on Singly Linked ListclassNode{constructor(newData){this.data=newData;this.next=null;}}// function to find out middle elementfunctionmiddle(start,last){if(start===null){returnnull;}if(start===last){returnstart;}letslow=start;letfast=start.next;while(fast!==last){fast=fast.next;slow=slow.next;if(fast!==last){fast=fast.next;}}returnslow;}// Function for implementing the Binary// Search on linked listfunctionbinarySearch(head,value){letstart=head;letlast=null;while(true){// Find middleletmid=middle(start,last);// If middle is emptyif(mid===null){returnfalse;}// If value is present at middleif(mid.data===value){returntrue;}// If start and last node are overlappingelseif(start===last){break;}// If value is more than midelseif(mid.data<value){start=mid.next;}// If the value is less than mid.elseif(mid.data>value){last=mid;}}// value not presentreturnfalse;}// Create a hard-coded linked list:// 1 -> 4 -> 7 -> 8 -> 9 -> 10lethead=newNode(1);head.next=newNode(4);head.next.next=newNode(7);head.next.next.next=newNode(8);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);letvalue=7;if(binarySearch(head,value)){console.log("Present");}else{console.log("Value not present");}
Output
Present
Time complexity: O(n) , where n is the number of nodes in linked list. Auxilliary Space: O(1)