GeeksforGeeks
A computer science portal for geeks Home Q&A Interview Corner Ask a question Feedback Contribute About us Subscribe Arrays Articles Bit Magic C/C++ Puzzles GFacts Linked Lists MCQ Misc Output Strings Trees
x=3
x=1
1/15
5/12/12
x=4
Method 1 (Linear Search) Linearly search for x, count the occurrences of x and return the count. Time Complexity: O(n) Method 2 (Use Binary Search) 1) Use Binary search to get index of the first occurrence of x in arr[]. Let the index of the first occurrence be i. 2) Use Binary search to get index of the last occurrence of x in arr[]. Let the index of the last occurrence be j. 3) Return (j i + 1); / i xi peeti ar]te rtrstecuto ocrecso x * f s rsn n r[ hn eun h on f curne f , ohriertrs-.* tews eun 1 / itcutitar] itx itn n on(n r[, n , n ) { iti / idxo frtocrec o xi ar0.-] n ; / ne f is curne f n r[.n1 itj / idxo ls ocrec o xi ar0.-] n ; / ne f at curne f n r[.n1 / gtteidxo frtocrec o x* * e h ne f is curne f / i=frtar 0 n1 x n; is(r, , -, , ) / I xdenteiti ar]te rtr - * * f os' xs n r[ hn eun 1 / i( = -) fi = 1 rtr i eun ; / Es gtteidxo ls ocrec o x Nt ta w * le e h ne f at curne f . oe ht e aeol loigi tesbra atrfrtocrec * r ny okn n h uary fe is curne / j=ls(r,i n1 x n; atar , -, , ) / rtr cut* * eun on / rtr ji1 eun -+;
/ i xi peeti ar]te rtrsteidxo FRTocrec * f s rsn n r[ hn eun h ne f IS curne o xi ar0.-] ohriertrs- * f n r[.n1, tews eun 1 / itfrtitar] itlw ithg,itx itn n is(n r[, n o, n ih n , n ) { i(ih> lw fhg = o) { itmd=(o +hg)2 /lw+(ih-lw/;/ n i lw ih/; *o hg o)2* i((md= 0| x>armd1)& armd = x f i = | r[i-] & r[i] = ) rtr md eun i;
www.geeksforgeeks.org/archives/12164 2/15
5/12/12
} rtr -; eun 1
es i( >armd) le fx r[i] rtr frtar (i +1,hg,x n; eun is(r, md ) ih , ) es le rtr frtar lw (i -) x n; eun is(r, o, md 1, , )
/ i xi peeti ar]te rtrsteidxo LS ocrec * f s rsn n r[ hn eun h ne f AT curne o xi ar0.-] ohriertrs- * f n r[.n1, tews eun 1 / itls(n ar] itlw ithg,itx itn n atit r[, n o, n ih n , n ) { i(ih> lw fhg = o) { itmd=(o +hg)2 /lw+(ih-lw/;/ n i lw ih/; *o hg o)2* i((md= n1| x<armd1)& armd = x) f i = - | r[i+] & r[i] = rtr md eun i; es i( <armd) le fx r[i] rtr ls(r,lw (i -) x n; eun atar o, md 1, , ) es le rtr ls(r,(i +1,hg,x n; eun atar md ) ih , ) } rtr -; eun 1 } / die pormt ts aoefntos* * rvr rga o et bv ucin / itmi( n an) { itar]={,2 2 3 3 3 3; n r[ 1 , , , , , } itx= 3 / Eeett b cutdi ar] n ; / lmn o e one n r[ itn=szo(r)szo(r[]; n iefar/iefar0) itc=cutar x n; n on(r, , ) pit( % ocr % tms" x c; rnf" d cus d ie , , ) gthr) eca(; rtr 0 eun ; } Time Complexity: O(Logn) Programming Paradigm: Divide & Conquer Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Send Be the first of
5/12/12
1. 2. 3. 4. 5.
Check for Majority Element in a sorted array Floor and Ceiling in a sorted array Program to count number of set bits in an (big) array Search an element in a sorted and pivoted array Count Inversions in an array
20 comments so far
1. Anuj Bansal says: November 13, 2011 at 6:53 PM Here is a code that also works in O(lgN). #nld<ti.> icuesdoh #nld<ahh icuemt.> #eieMX1 dfn A 2 itnme(n aMX,itlw ithg,itx { n ubrit [A] n o, n ih n ) i(o < hg){ flw = ih itmdij n i,,; md=(o+ih/; i lwhg)2 i([i]= x { famd = ) i=nme(,o,i-,) ubralwmd1x; j=nme(,i+,ihx; ubramd1hg,) i( ! - & j! -) fi = 1 & = 1 rtr ij1 eun ++; es i( = - & j! -) le fi = 1 & = 1 rtr j1 eun +; es i(= - & i! -) le fj= 1 & = 1 rtr i1 eun +; es le rtr 1 eun ; } es i([i]>x le famd ) rtr nme(,o,i-,) eun ubralwmd1x; es le rtr nme(,i+,ihx; eun ubramd1hg,) } es le rtr -; eun 1 }
www.geeksforgeeks.org/archives/12164 4/15
5/12/12
itmi( { n an) itaMX=1133337771,11} n [A]{,,,,,,,,,11,2; pit(%\"nme(,,A-,); rnf"dn,ubra0MX17) rtr 0 eun ; } Reply 2. Ankur says: October 4, 2011 at 2:46 AM If mid==0 or mid==n-1 then the function returns mid Now if the element is not present then the result will be wrong Here i think we should put a check before return mid statement that if(mid==0){ if(x!=a[mid]) return -1 } similarly for Last func Reply 3. LoneShadow says: August 18, 2011 at 6:53 AM The function first doesnt seem to work for the following input. For example, array is 0,1,1,2,3, and I am looking for the first occurrence of 1. Start with low=0, high= 4, x=1. 1. Mid = 2, and since arr[mid-1] is not less than x(arr[mid-1] is arr[1], which is 1), it will end up calling the function again with parameters 0, 1 2. With 0,1 as low and high mid will be (0+1)/2, which is 0. The first conditional wil fail,( mid == 0, but the && part is not true, a[mid] is a[0], which is NOT equal to 1). So the function will be called again with low, mid-1, which is 0,0. 3. This will eventually return -1, which is wrong. Also, not really sure why n is being passed into first/last. Not being used as far as I can see. Reply LoneShadow says: August 18, 2011 at 6:57 AM One fix I can think off the top of my head is to call the function again with low, mid instead of low, mid-1, since you want to include the value of mid itself (its
www.geeksforgeeks.org/archives/12164 5/15
5/12/12
equal, not less or more to be excluded). Reply LoneShadow says: August 18, 2011 at 7:10 AM Sorry, my bad. Worked it out. Reply 4. skulldude says: July 16, 2011 at 3:54 PM Well, can someone tell me why in the second method is the condition (m==0) included while checking if the middle element is the required element? i((md= 0| x>armd1)& armd = x f i = | r[i-] & r[i] = ) Reply hari6988 says: August 11, 2011 at 11:22 PM if mid was 0 , arr[mid-1] will reference arr[-1] and it will cause the error .same case with mid==n-1||x<arr[mid+1] Reply 5. Jatin Sanghvi says: July 12, 2011 at 1:52 AM shouldn't work. take arr = [1,3] and search for 2. Reply GeeksforGeeks says: July 12, 2011 at 9:55 AM @Jatin Sanghvi: The given code works fine for your example. It returns -1 when the given number is not present. Reply 6. foobar says: June 19, 2011 at 10:13 PM pbi sai vi Cutubrfcuecs) ulc ttc od onNmeOOcrne( { / * *Cuttenme o ocrecsi asre ary on h ubr f curne n otd ra
www.geeksforgeeks.org/archives/12164 6/15
5/12/12
*Gvnasre aryar]adanme x wieafnto t ie otd ra r[ n ubr , rt ucin ** / it]ar={,1 2 2 2 2 3} n[ r 1 , , , , , ,; itn=2 n ; itrs=AryBnrSac(r,2; n e ra.iayerhar ) itfud=rs n on e; itcut=0 n on ; i(e >0 frs ) { cut+ on+; } wiear-rs = 2 hl(r[-e] = ) { cut+ on+; } rs=fud e on; wiear+rs =2 hl(r[+e] =) { cut+ on+; } CnoeWieiers; osl.rtLn(e) } Reply 7. saji says: May 12, 2011 at 1:48 PM while invoking the method last , will using the args last(arr, i, n-1, x, n) instead of last(arr, 0, n-1, x, n) cause any issues? Reply GeeksforGeeks says: May 12, 2011 at 2:44 PM @saji: Thanks for suggesting the optimization. It doesn't cause any problem. We have updated the code with the suggested changes.
www.geeksforgeeks.org/archives/12164 7/15
5/12/12
Reply 8. nandini says: May 5, 2011 at 2:43 AM Isn't the complexity of the algorithm in Method2 O(n) in the worst case? eg: {2,2,2,2,2} program will start from mid-index and then will shift one-by-one towards left to find 'first' and then one-by-one right to find 'last' in each loop. Reply Sandeep says: May 5, 2011 at 7:52 AM @nandini: Please take a closer look at the program, it recursively divide the array into two halves. Time complexity is: T(n) = T(n/2) + C which is O(Logn) Reply thechamp says: May 10, 2011 at 9:59 PM you have chosen an example where number of elements are so less that it appears a sequential search but it is a binary search only Reply 9. WgpShashank says: May 3, 2011 at 6:11 PM Hi Sandeep It Can be done more simply using Modified Binary Search Algorithm calculate mid=low+high/2; if(a[mid]>num) search in right side & set low=mid+1 & return ; else if(a[mid] search in left side of mid set high=mid-1 & return ; else //its important instead of just of printing the num or incrementing the counter //i tried if you will do like this then it will be O(n) not O(logn) , si i will add 1 to recursively call for left side + recursively call for right side so every time this line executes we are incrementing the counter & return 1+left_binsearch()+right_binsearch thus it will be in O(logn) Here is the Code
www.geeksforgeeks.org/archives/12164 8/15
5/12/12
#nld<ti.> icuesdoh itCutita] itvle itlw ithg) n on(n [, n au, n o, n ih { itmd n i; i (ih<lw f hg o) rtr 0 eun ; md=lw+(ih-lw/; i o hg o)2 i ([i]>vle f amd au) rtr Cuta vle lw md-1; eun on(, au, o, i ) es i ([i]<vle le f amd au) rtr Cuta vle md+1 hg) eun on(, au, i , ih; es le rtr 1+Cuta vle lw md-1 + eun on(, au, o, i ) Cuta vle md+1 hg) on(, au, i , ih; } itmi( n an) { ita]={,2 2 3 3 3 3; n [ 1 , , , , , } itvle=3 n au ; pit(%\" Cuta vle 0 szo()szo(n)1) rnf"dn, on(, au, , iefa/iefit-); rtr 0 eun ; } its running for may test cases Correct me if Anything Wrong Run Here https://ideone.com/g7koI run Here Reply Sandeep says: May 3, 2011 at 6:49 PM @WgpShashank: Thanks for suggesting a new method. The approach looks fine, but the time complexity in worst case is O(n). Consider the case when all elements are same. ita]={,3 3 3 3 3 3; n [ 3 , , , , , } itvle=3 n au ; In this case, the time complexity can be written as T(n) = 2*T(n/2) + C which is O(n) Reply
www.geeksforgeeks.org/archives/12164 9/15
5/12/12
WgpShashank says: May 27, 2011 at 8:47 PM @sandeep Thanks For Pointing out ..yes it will O(n) in this scenario Reply Yogesh says: September 29, 2011 at 12:12 AM i think that is the only case which is making its time complexity O(n)... that can be covered by adding line
i ([ih = vle& alw = vle rtr (ihl f ahg] = au & [o] = au) eun hgat the beginning of the count function Correct me if i am wrong somewhere. Reply saurabh says: February 4, 2012 at 4:35 PM i think Time compl. will be O(logn) / \ Tn2 (/) Tn2 (/) / \ / \ Tn4 Tn4 Tn4 Tn4 (/) (/) (/) (/) ................ ............... Worst case will be longest height of above recursion tree.... let k will be max height.....and also we see terms at each level forms a G.P(1,1/2,1/4,...) and through calculas stuff we know this will be a convergence series....and sum of node at each level is n(n/2+n/2)....n(1/2)^k< =1 k>=log2(n)..nearly....hence time compl will b O(logn) Reply Tn ()
Comment
www.geeksforgeeks.org/archives/12164 10/15
5/12/12
[oreoelnug=C] succd agae"" / Pseyu cd hr (o mydlt teelns * at or oe ee Yu a eee hs ie i ntwiigcd)* f o rtn oe / [succd] /oreoe
Search
Popular Tags
GATE Java Dynamic Programming Backtracking Pattern Searching Divide & Conquer Graph Operating Systems Recursion
www.geeksforgeeks.org/archives/12164
11/15
5/12/12
Popular Posts
All permutations of a given string Memory Layout of C Programs Understanding extern keyword in C Median of two sorted arrays Tree traversal without recursion and without stack! Structure Member Alignment, Padding and Data Packing Intersection point of two Linked Lists Lowest Common Ancestor in a BST. Check if a binary tree is BST or not Sorted Linked List to Balanced BST
www.geeksforgeeks.org/archives/12164
12/15
5/12/12
250
Subscribe
tree to file
Last Post By: Dheeraj Inside: Interview Questions
www.geeksforgeeks.org/archives/12164 13/15
5/12/12
FB interview question
Last Post By: ranganath111 Inside: Interview Questions
numeric puzzle
Last Post By: asm Inside: Algorithms
Forum Categories
Interview Questions C/C++ Programming Questions Algorithms Trees specific questions Linked List specific questions Multiple Choice Questions Object oriented queries GPuzzles
www.geeksforgeeks.org/archives/12164 14/15
5/12/12
Recent Comments
Venki on Structure Member Alignment, Padding and Data Packing avi on Structure Member Alignment, Padding and Data Packing atul on A Program to check if strings are rotations of each other or not Venki on Structure Member Alignment, Padding and Data Packing rahul on Dynamic Programming | Set 13 (Cutting a Rod) Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence) Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence) avi on Structure Member Alignment, Padding and Data Packing @geeksforgeeks, Some rights reserved Powered by WordPress & MooTools, customized by geeksforgeeks team
www.geeksforgeeks.org/archives/12164
15/15