Search code examples
algorithmmathcomplexity-theorydivisionfind-occurrences

Occurrence of number in array,with complexity log n algorithm and c


hi genius i wish you good day Situation:

T [M] an array sorts in ascending order.

Write an algorithm that calculates the number of occurrences of an integer x in the array T[M].
the number of comparison of x to the elements of T, must be of order log n

My attempt is:

def Occurrence(T,X,n):{
   
 
       if ( n=0 ){ return 0;}
        else { 

            Occurrence(T,X,n/2);

            if( T[n]==X ){  return 1+Occurrence(T,x,n/2); }
            else { return Occurrence(T,x,n/2); }

 
 }the end of code
complexity is :
                   0 if n=0
we have      O(n)={
                   1+O(n/2) if n>0
O(n)=1+1+1+....+O(n/2^(n))=n+O(2/2^(n))
when algorithm stopp if{existe k  n=2^(k),so   O(n)=n+1 } 
n/2^(n)=1)  =>   O(n)=log(n)+1, so you think my code is true ?
</pre>

Solution

  • if the array is sorted

    import bisect 
    
    T = [1, 3, 4, 4, 4, 6, 7]
    x = 4
    right = bisect.bisect(T, x)
    if(right == 0 or T[right - 1] != x):
        print("Count:0")
    else:
        left = bisect.bisect_left(T, x)
        print("Count:", right - left)
    

    2Log(n)