×

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

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.

Bubble Sort vs Quick Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Quick Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Heap Sort vs Merge Sort

In this article, we are going to discuss the Heap Sort, Merge sort and the difference between them. What is Heap Sort? Heap – A heap is an abstract data type categorised...

7 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

Interval Tree

Interval Tree Interval Tree: The concept is to increase a Binary Search Tree self-balancing such as Red Black Tree, and AVL Tree, so that every feature can be completed in time O(Logn). Each Interval...

4 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Find out the area between two concentric circles

You have given two values of the radius of two circles. You have to find out the area between these two circles. Let's take an example - For the above diagram,...

3 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Vertical Order Traversal of Binary Tree

Implementation #include <iostream> #include <vector> #include <map> using namespace std; // representing the primary model of a binary tree node. struct _nod { int ky; _nod *Lft, *Rt; }; // establishing a new function representing the new binary tree node. struct _nod*...

5 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Write Main Difference Between Tree and Graph in Data Structures

Graph: The graph has two sets, which are considered V and E. These vertices are also called nodes, and edges are referred to as arcs connecting any two nodes in a...

4 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.