Professional Documents
Culture Documents
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
5/12/12
Asked by rajk Method 1 (Linear Search) Linearly search for an index i such that arr[i] == i. Return the first such index found. Thanks to pm for suggesting this solution. itlnaSac(n ar] itn n iererhit r[, n ) { iti n ; fri=0 i<n i+ o( ; ; +) { i(r[]= i fari = ) rtr i eun ; } / I n fxdpitpeette rtr - * * f o ie on rsn hn eun 1 / rtr -; eun 1
/ Die pormt cekaoefntos* * rvr rga o hc bv ucin / itmi( n an) { itar1]={1,-,0 3 1,1,3,5,10; n r[0 -0 1 , , 0 1 0 0 0} itn=szo(r)szo(r[]; n iefar/iefar0) pit(FxdPiti %" lnaSac(r,n) rnf"ie on s d, iererhar ); gthr) eca(; rtr 0 eun ; } Time Complexity: O(n)
Method 2 (Binary Search) First check whether middle element is Fixed Point or not. If it is, then return it; otherwise check whether index of middle element is greater than value at the index. If index is greater, then Fixed Point(s) lies on the right side of the middle point (obviously only if there is a Fixed Point). Else the Fixed Point(s) lies on left side. itbnrSac(n ar] itlw ithg) n iayerhit r[, n o, n ih { i(ih> lw fhg = o) { itmd=(o +hg)2 /lw+(ih-lw/;/ n i lw ih/; *o hg o)2*
www.geeksforgeeks.org/archives/15946 2/19
5/12/12
i(i = armd) fmd = r[i] rtr md eun i; i(i >armd) fmd r[i] rtr bnrSac(r,(i +1,hg) eun iayerhar md ) ih; es le rtr bnrSac(r,lw (i -); eun iayerhar o, md 1)
/ Die pormt cekaoefntos* * rvr rga o hc bv ucin / itmi( n an) { itar1]={1,-,0 3 1,1,3,5,10; n r[0 -0 1 , , 0 1 0 0 0} itn=szo(r)szo(r[]; n iefar/iefar0) pit(FxdPiti %" bnrSac(r,0 n1) rnf"ie on s d, iayerhar , -); gthr) eca(; rtr 0 eun ; } Algorithmic Paradigm: Divide & Conquer Time Complexity: O(Logn) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Send 5 people
You may also like following posts 1. 2. 3. 4. 5. Search an element in a sorted and pivoted array Find whether an array is subset of another array | Added Method 3 Count the number of occurrences in a sorted array Check for Majority Element in a sorted array Floor and Ceiling in a sorted array Microsoft Private Cloud
Microsoft Private Cloud: Built for the Future. Ready Now. Learn More!
Microsoft.com/readynow
25 comments so far
1. Anon says:
www.geeksforgeeks.org/archives/15946 3/19
5/12/12
April 21, 2012 at 6:40 PM The binary search method will not work in case of duplicate elements in the array, because we can't eliminate one part of the array in each iteration. Reply 2. Avi says: April 12, 2012 at 8:17 PM #nld<ti.> icuesdoh #nld<oi.> icuecnoh itmi( n an) { itar]={1,-,3 4 7 9; n r[ -0 5 , , , } itln=szo(r)szo(n) n e iefar/iefit; sai itfa; ttc n lg itnm=-; n u 1 friti=0 iln i+ o(n ; <e; +) { i(r[]= i fari = ) { fa =1 lg ; nm=ari; u r[] bek ra; } } pit(% \" nm; rnf"d n, u) gth) ec(; } Reply 3. PsychoCoder says: March 10, 2012 at 1:14 PM In the function this portion is fixed irrespective of the given data. i(i >armd) fmd r[i] rtr bnrSac(r,(i +1,hg) eun iayerhar md ) ih; es le rtr bnrSac(r,lw (i -); eun iayerhar o, md 1) So, if my input is
www.geeksforgeeks.org/archives/15946 4/19
5/12/12
itar1]={1,-,0 6 1,1,3,5,10 9; n r[0 -0 1 , , 0 1 0 0 0, } then 5(mid) < 11 (arr[mid]) so it will neglect right hand side the value '9' which is placed at arr[9]. Reply Yogesh Batra says: April 8, 2012 at 4:12 PM This is clearly given that sequence is in increasing order, find some other counter example for binary look up method. Reply 4. kartikaditya says: February 20, 2012 at 11:22 AM #include <iostream> #include <stdio.h> using namespace std; int getFixedPoint(int a[], int n) { int start = 0, end = n - 1, mid = 0; while (start <= end) { mid = (start + end) >> 1; if (a[mid] == mid) { return mid; } else if (a[mid] < mid) { start = mid + 1; } else { end = mid - 1; } } return -1; } int main() { int a1[] = {-10, -5, 0, 3, 7}; cout << getFixedPoint(a1, 5) << endl; int a2[] = {0, 2, 5, 8, 17}; cout << getFixedPoint(a2, 5) << endl; int a3[] = {-10, -5, 3, 4, 7, 9}; cout << getFixedPoint(a3, 6) << endl; int a4[] = {-10, 1, 2, 3, 10, 11, 30, 50, 100}; cout << getFixedPoint(a4, 9) << endl;
www.geeksforgeeks.org/archives/15946 5/19
5/12/12
return 0; } Reply 5. vijay_kansal says: February 15, 2012 at 3:25 PM An optimized algorithm for the case when elements can be repeated in the array : itfxdp(n *,n n n ie_tit ait ) { itl0hn1mi n =,=-,,; wiel=) hl(<h { m(+)2 =lh/; i([]=) fam>0 hm1 =-; es le lm1 =+; }/fnigte1teeeti wl b al)>0 / idn h s lmn(t il e [] = friliniai) o(=;<;=[] { i([]=) fai=i rtr i eun ; } rtr -; eun 1 } The algo will return 1st element that is a fixed pt. Reply vijay_kansal says: February 19, 2012 at 10:35 AM An error correction, Replace the if condition of while loop by : i([]=) fam>m Reply 6. Nages says: February 10, 2012 at 6:55 AM pbi casFxdonIAry{ ulc ls iePitnra pbi sai vi mi(tig]ag { ulc ttc od anSrn[ r)
www.geeksforgeeks.org/archives/15946 6/19
5/12/12
itar]=nwit]{-0 -,0 3 7} n r[ e n[ 1, 5 , , ; Sse.u.rnl(iePitar) ytmotpitnfxdon(r); ar=nwit]{0 2 5 8 1 } r e n[ , , , , 7 ; Sse.u.rnl(iePitar) ytmotpitnfxdon(r); ar=nwit]{-0 -,3 4 7 9} r e n[ 1, 5 , , , ; } Sse.u.rnl(iePitar) ytmotpitnfxdon(r);
pbi sai itfxdon(n[ ar { ulc ttc n iePitit] r) itps=-; n o 1 fr(n i=0 i<arlnt; { o it ; r.egh) i ( = ari) f i = r[] rtr i eun ; es i ( <ari) le f i r[] i=ari; r[] es le +i +; } } rtr ps eun o;
Reply 7. Karthick says: December 27, 2011 at 6:19 PM I think, the following code can find the first Fixed Point. It would be good if someone can check this code for correctness. int findFirstFixedPoint(int a[],int length) { if(length==0){ return -1; } int start=0,end=length-1,middle; while(start<=end) { middle=(start+end)/2; if(a[middle]==middle) {
www.geeksforgeeks.org/archives/15946 7/19
5/12/12
if(middle==start || a[middle-1]!=middle-1){ return middle; } end=middle-1; } else if(a[middle]<middle){ start=middle+1; } else{ end=middle-1; } } return -1; } Reply Karthick says: December 27, 2011 at 6:25 PM Sorry for posting without the sourcecode tags itfnFrtiePititlnt) n idisFxdon(n egh { i(egh=) rtr -;} flnt=0{ eun 1 itsat0edlnt-,ide n tr=,n=egh1mdl; wiesat=n) hl(tr<ed { mdl=sated/; ide(tr+n)2 i([ide=mdl) famdl]=ide { i(ide=tr | amdl-]=ide1{rtr fmdl=sat | [ide1!mdl-) eun edmdl-; n=ide1 } es i([ide<ide{satmdl+;} le famdl]mdl) tr=ide1 es{edmdl-;} le n=ide1 } rtr -; eun 1 } Reply 8. kaka09 says: December 14, 2011 at 7:19 PM #nld<ti.> icuesdoh itmi n an { itnijfa=1ps n ,,,lg-,o; saf"d,n;) cn(%"&)( itan; n [] fri0ini+ o(=;<;+) saf"d,ai) cn(%"&[]; i0 =;
www.geeksforgeeks.org/archives/15946 8/19
5/12/12
wieai+<) hl([+]0 frjijnj+ o(=;<;+) { i(=aj) fj=[] { fa=; lg0 psj o=; bek ra; } } i(lg=) ffa!0 pit(nme ntfud!) rnf"ubr o on!"; es le pit(nme fuda idx%\" ps; rnf"ubr on t ne dn, o)
Reply 9. kaka09 says: December 14, 2011 at 7:19 PM #nld<ti.> icuesdoh itmi( n an) { itnijfa=1ps n ,,,lg-,o; saf"d,n; cn(%"&) itan; n [] fri0ini+ o(=;<;+) saf"d,ai) cn(%"&[]; i0 =; wieai+<) hl([+]0 frjijnj+ o(=;<;+) { i(=aj) fj=[] { fa=; lg0 psj o=; bek ra; } } i(lg=) ffa!0 pit(nme ntfud!) rnf"ubr o on!"; es le pit(nme fuda idx%\" ps; rnf"ubr on t ne dn, o) } Reply 10. punit says:
www.geeksforgeeks.org/archives/15946 9/19
5/12/12
December 3, 2011 at 1:09 PM for handling equal values like [-1, 0, 4, 4, 4, 4, 4] just tweak binary search as followsint bs(vector v, int l, int r) { int m = (l+r)/2; if(l > r) return -1; if(v[m] == m) return m; if((v[m] > m) && (v[m] != v.at(m+1))) { return bs(v, l, m-1); } else return bs(v, m+1, r); } Reply AG says: December 29, 2011 at 2:56 PM I think it fails for this test case:[0, 2, 5, 5, 5, 6, 7]
/ Pseyu cd hr (o mydlt teelnsi ntwii * at or oe ee Yu a eee hs ie f o rt Reply Yogesh Batra says: April 8, 2012 at 4:22 PM It's working, I don't think there is any problem with the above code. Reply yogendra says: April 9, 2012 at 9:31 PM @Yogesh I checked the above code is failing in case of [0, 2, 5, 5, 6, 7] in first Itr l=0,r=5 => m=2; so a[2]>2 and here a[2]==a[3]==5 so l=3;
www.geeksforgeeks.org/archives/15946 10/19
5/12/12
in second Itr l=3,r=5 =>m=4; s0 a[4]>6 hence it will return -1; int next iter. Reply 11. punit says: December 3, 2011 at 1:00 PM /* Paste your code here (You may delete these lines if not writing code) */ [#include using namespace std; #include int bs(vector v, int l, int r) { int m = (l+r)/2; if(l > r) return -1; if(v[m] == m) return m; if(v[m] > m) { return bs(v, l, m-1); } else return bs(v, m+1, r); } void Fp(vector v, int l, int r) { int index; static int flag = true, Index = 0; index = r; while(1) { index = bs(v, l, index-1); if(index == -1) { if(flag == false) { cout<<"not found.\n"; return; } cout<<"found at index = "<<Index<<endl; break; }
www.geeksforgeeks.org/archives/15946 11/19
5/12/12
Index = index; flag = true; } } int main() { vector v; v.push_back(-1); v.push_back(0); v.push_back(2); v.push_back(5); Fp(v, 0, v.size()); return 0; }] Reply 12. Daniel says: December 1, 2011 at 3:18 PM The non-distinct case would be interesting. Reply kartik says: December 1, 2011 at 8:49 PM I don't think binary search can be applied in case of non-distict case. For example, {-1, 4, 4, 4, 4, 4, 4}. We go to middle index 3 and see value is greater then index. We can't have a logic to look for left side or right side as array could be {-1, 0, 2, 4, 6, 8, 10} or {-1, 4, 4, 4, 5, 5, 5}. Let me know your thoughts. Reply 13. krishna says: December 1, 2011 at 12:11 PM The problem would be more interesting if we ask for the first Fixed Point instead of a Fixed Point. Reply kartik says: December 1, 2011 at 12:20 PM @Krishna: Thanks for suggesting a more advanced version of the problem. The method 1 anyways finds the first FP. The method 2 can also be tweaked to find the first FP.
www.geeksforgeeks.org/archives/15946 12/19
5/12/12
Reply Venki says: December 1, 2011 at 4:22 PM @krishna, Good question. Binary search is such a powerful technique, some times, we miss to note its power. Solution to your question is given below. Let me know if there are any corner cases. itbnrSac(n A] itl itr n iayerhit [, n , n ) { itmd n i; ittae =-; n rcd 1 wie ( -l >1) hl( r ) { md=l+( -l/; i r )2 i(Amd = md) f [i] = i tae =md rcd i; / CC+sateog t cnue / /+ mr nuh o ofs (i < Amd ?r:l =md md = [i] ) i;
Reply Jing says: December 2, 2011 at 11:11 AM For A=[-1, 0, 2], it seems to return -1 instead of 2, doesn't it?
/ Pseyu cd hr (o mydlt teelnsi nt * at or oe ee Yu a eee hs ie f o Reply Venki says: December 1, 2011 at 4:23 PM Driver code. itmi( n an) {
www.geeksforgeeks.org/archives/15946 13/19
5/12/12
itar]={1,1 2 3 1,1,3,5,10; n r[ -0 , , , 0 1 0 0 0} itn=szo(r)szo(r[]; n iefar/iefar0) pit(FxdPiti %" bnrSac(r,0 n1) rnf"ie on s d, iayerhar , -); } rtr 0 eun ;
Reply Venki says: December 2, 2011 at 11:41 AM @Jing, thanks for pointing the error. Given below is updated one. #nld <ti.> icue sdoh itbnrSacLf(n A] itl itr n iayerhetit [, n , n ) { itmd n i; ittae =-; n rcd 1 wie ( -l >1) hl( r ) { md=l+( -l/; i r )2 i(Amd = md)tae =md f [i] = i rcd i; } (i < Amd ?r:l =md md = [i] ) i;
i(Ar = r)tae =r f [] = rcd ; i(Al = l)tae =l f [] = rcd ; } rtr tae; eun rcd
itbnrSacRgtitA] itl itr n iayerhih(n [, n , n ) { itmd n i; ittae =-; n rcd 1 wie ( -l >1) hl( r ) { md=l+( -l/; i r )2 i(Amd = md)tae =md f [i] = i rcd i;
www.geeksforgeeks.org/archives/15946 14/19
5/12/12
i(Al = l)tae =l f [] = rcd ; i(Ar = r)tae =r f [] = rcd ; } rtr tae; eun rcd
pit(FxdPiti %\" bnrSacLf(r,0 n1) rnf"ie on s dn, iayerhetar , -) pit(FxdPiti %\" bnrSacRgtar 0 n1 rnf"ie on s dn, iayerhih(r, , -) } rtr 0 eun ;
Reply
Comment
Name (Required) Website URI code between sourcecode tags) Email (Required) Your Comment (Writing code? please paste your
[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
www.geeksforgeeks.org/archives/15946
15/19
5/12/12
Popular Tags
GATE Java Dynamic Programming Backtracking Pattern Searching Divide & Conquer Graph Operating Systems Recursion
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/15946
16/19
5/12/12
250
Subscribe
tree to file
Last Post By: Dheeraj Inside: Interview Questions
www.geeksforgeeks.org/archives/15946 17/19
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/15946 18/19
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/15946
19/19