Binary Search - Time Complexity

Time Complexity of Binary Search Algorithm





Algorithm:

 

    Int BinarySearch(int Array[], int value, int left, int right){

               Int mid=(left+right)/2

 

 

If(Array[mid]== value){

Return mid;

}elif(left>right){

Return -1;

}elif(Array[mid] > value){

BinarySearch(Array,left,mid-1);

}else{

 

BinarySearch(Array, mid+1,right);

}

 

End if

 

}






Let N be the Size of the Binary tree

 

T(N) =  C +  T(N/2)   ------ 1

T(N/2) = C + T (N/4) ------2


Substitute 2 à 1

T(N) = 2C + T(N/4)    -------3

T(N/4) = C + T(N/8)  --------4



Substitute 4 à 3

 

T(N) = 3C + T(N/8) ------5

 

pattern

 

T(N) = iC + T(N/2i      where I is an integer

 

 

At some point , as N/2i diminishes , we reach only 1 element,

 

So        

                 T(N) = T(1)

                  T(N)= T(N/2i) + iC   --------6

 

à   N/2= 1

è  N = 2i

 

 

 

Take log2 on both sides

 

log2 N = log2 2i

log2 N = i  ---------7

 

Substitute 7 à 6

 

T(N) = T(N/2 log2N) + C log2 N

T(N) = T(N/N) + C log2 N

T(N) = T(1) + C log2 N

Since T(1) is a constant value,


T(N) = K + C log2 N


To find the time complexity we need to remove constants,

 

Time complexity = T(N) = O(log2 N)

 

F(N) = O(log2 N)

Comments

Popular posts from this blog

Insertion Sort - Time Complexity

Selection Sort - Time Complextity

Quick Sort - Time Complexity