×

Binary Search

In this searching technique, the given element is compared with the middle element of the list.

  • If both elements are equal, it returns the index value.
  • If both elements are not equal, we check whether the given element is larger or smaller than the middle element.
  • If the given element is smaller than the middle element, we will repeat the same process in the smaller part of the list.
  • If the given element is larger than the middle element, we will repeat the same process in the larger part of the list.
ComplexityBest caseAverage caseWorst case
TimeO(1)O(log n)O(log n)
Space  O(1)
Binary_Search( )
Step 1: SET BEG = lower_bound, END = upper_bound, FLAG = - 1
Step 2: Repeat Steps 3 and 4 while BEG <=END
Step 3: SET MID = (BEG + END)/2
Step 4: if A[MID] = VAL
             SET FLAG = MID
             print “index value of the element”
             Go to Step 6
             else if A[MID] > VAL
             else END = MID - 1
             else
             SET BEG = MID + 1
             // end of if
             // end of loop
Step 5: if FLAG = -1
             print " element is not found in this list "
             // end of if
Step 6: exit  

For example, suppose you have the following array, and you have to search 30 in it.

Iteration 1: BEG = 0           
          END = 8       
              MID = (BEG + END) / 2            
                     (0 + 8) / 2 = 4       
              A[MID] = VAL      
               A[4] = 30      
               35 ? 30         // not equal       
Iteration 2: BEG = 0                     END = MID – 1                              = 4 – 1 = 3                     MID = (0 + 3) / 2                              = 1                     A[1] = VAL                     27 ? 30         // not equal  
Iteration 3: BEG = MID + 1                              = 1 + 1                              = 2                     END = 3                     MID = (2 + 3) / 2                              = 2                      A[2] = VAL                      29 ? 30         // not equal
Iteration 4: BEG = MID + 1                              = 2 + 1                              = 3                     END = 3                     MID = (3 + 3) / 2                              = 6                     A(3) = VAL                       30 = 30            // equal                                       
Index value of 32 is 3.

Binary search program in C language  

#include<stdio.h>
   int binarySearch(int[], int, int, int);   
void main () 
  {     
 int arr[10] = {6,  9, 12, 23, 35, 46, 68, 90, 96, 120};  
     int item, location=-1;     
   printf("enter the search element ");    
   scanf("%d",&item);   
    location = binarySearch(arr, 0, 9, item); 
      if(location != -1)     
   {     
      printf("element index value is %d",location);  
     }      
 else      
 {         
  printf("element not found"); 
      }  
 }  
  int binarySearch(int a[], int beg, int end, int item) 
  {   
    int mid;   
    if(end >= beg)   
     {          
    mid = (beg + end)/2;  
         if(a[mid] == item)
           {         
      return mid+1;  
         }         
  else if(a[mid] < item)   
         {         
      return binarySearch(a,mid+1,end,item);   
        }      
    else       
     {         
      return binarySearch(a,beg,mid-1,item);  
         }         
    }    
   return -1; 
   }    

Output

enter the search element
35
element index value is 4

Related Topics

Equal Sum

Find an element in array such that the sum of left array is equal to the sum of right array You have been given an array of numbers. You have to...

4 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

Deque in Data Structure

Deque A deque referred as “Double-Ended Queue”, is a linear collection of data items same like queue data structure. deque has two ends, front end and rear end, deque is the...

27 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

5 minutes read.

Detect Loop in Linked List: Data Structure

Detect the Loop in Linked List: In this problem, we will be seeing some technique through which we can detect the loop in linked list. We will discuss each technique...

3 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Threaded Binary Trees

Introduction Threaded Binary Trees (TBTs) are an enhancement of normal binary trees intended for in-order traversal only. This means that this data structure is developed with the objective of making the...

12 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

5 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Given a Generate all Structurally Unique Binary Search Trees

Implementation // Creating a C++ program that will help us build all the binary search trees for the keys from 1 to n.  #include <bits/stdc++.h> using namespace std; // creating a structure that will...

8 minutes read.

What is a Height-Balanced Tree in Data Structure

A height-balanced tree is a type of binary tree. If the absolute difference between the heights of the left and right subtree is less than or equal to 1, then...

6 minutes read.

Stack Using Linked List

In the linked list implementation of the stack, we use a linked list as the primitive data structure to create the stack. It is called the dynamic implementation of the...

6 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.

Counting Sort

Counting Sort: Counting sort is a sorting algorithm that is used to sort the elements of the array within a specific range. It counts the same element number of the...

3 minutes read.