-2

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>
  • 4
    1. Binary Search for the first occurrence 2. Binary Search for the last occurrence. What is the problem with that? – Abhinav Mathur Jan 16 '21 at 11:05
  • first of all thank you for reacting.the situation Not saying first occurrence,i want all occurrence,I ask if these answer is responding to question or exist other answer to solve this problem or my attempt are not correct . –  Jan 16 '21 at 11:10
  • 1
    Your code currently fails to achieve the log(N) complexity in the case where the array has ~N occurences of the number you are searching for since in such case you need to perform ~N additions. Also I'm not sure about the `else {return Occurence; }` depending on a language this is either not possible or returning a pointer to a function which probably isn't what you wanted. – Shamis Jan 16 '21 at 11:19
  • thank you i've edited else {return Occurrence; }, –  Jan 16 '21 at 11:24

2 Answers2

1

Look at binary search variants that give the leftmost and the rightmost indices of needed element, then return index_difference + 1

You can use lower_bound and upper_bound in C++ STL, bisect_left and bisect_right in Python, similar functions if available, or implement pseudocode from Wiki citation.

MBo
  • 77,366
  • 5
  • 53
  • 86
0

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)

Harney
  • 352
  • 1
  • 4