0

I wrote an algorithm for finding a key in sorted array of infinite integers.

 findKey(int k, int start, int end)
     int mid = (start + end)/2

     if (k < array[mid])
         findKey(k, start, mid)
     else if (k > array[mid])
         findKey(k, mid+1, end)
     else 
         return mid

I want to know the time complexity of this algorithm. Is it o(logn)? I'm really confused, can anyone explain? Also let me know if there are any flaws in here. Thanks in advance.

5
  • 1
    What are "infinite integers"? And how is this any different from an ordinary binary search? Commented Apr 23, 2013 at 15:52
  • 1
    en.wikipedia.org/wiki/Binary_search_algorithm Commented Apr 23, 2013 at 15:53
  • The number of integers is unknown, assuming it as infinite. Commented Apr 23, 2013 at 15:53
  • Previous question on SO here and here. The first link talks about an /infinite/ array and binary search. Commented Apr 23, 2013 at 15:57
  • 2
    If you are assuming the numbers can be infinitely large, then you can't assume that your arithmetic operators are O(1). Commented Apr 23, 2013 at 15:57

2 Answers 2

1

Let we have array with stored value enter image description here

Suppose we want to find the key=20, we call findkey(20,1,8) with parameters k=20, start=1 and end = 8

Series of function calls

enter image description here

Recurrence relation :

T(n)  = T(n/2)+c
 expanding…
          =T(n/2^2)+c+c
          =T(n/2^3)+c+c+c

Kth time expanding…

          = c+c+c+c+c . .. .. . .. . . .  .T(n/2^k)

Let at kth time array size become 1,
we assume it as a base condition for recurrence.
Thus , 
   n/2^k = 1
      n  = 2^k
Taking log both sides ..
    log n = k

 time complexity of recurrence..

   T(n) = c* log n 
        = O(log n) 
Sign up to request clarification or add additional context in comments.

Comments

0

What you've made is the binary search algorithm, or something close to it. This algorithm is O(log n).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.