fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int BINARY_SEARCH(int *ARR,int &N,int &ITEM)
  5. {
  6. int LB=0,UB=N-1;
  7. while(LB<=UB)
  8. {
  9. int MID=(LB+UB)/2;
  10.  
  11. if(ARR[MID]==ITEM)
  12. return MID;
  13. else if(ARR[MID]<ITEM)
  14. LB=MID+1;
  15. else
  16. UB=MID-1;
  17. }
  18. return -1;
  19. }
  20.  
  21.  
  22. int main()
  23. {
  24. int N,ITEM,lOC;
  25. cin>>N;
  26. int ARR[N];
  27. for(int i=0;i<N;i++)
  28. cin>>ARR[i];
  29. cin>>ITEM;
  30.  
  31. int LOC=BINARY_SEARCH(ARR,N,ITEM);
  32.  
  33. if(LOC==-1)
  34. cout<<"ITEM is not in the ARRAY" <<endl;
  35. else
  36. cout<<"ITEM "<<ITEM<<" is in the location "<<LOC+1<<endl;
  37.  
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5272KB
stdin
7
11 13 14 16 17 19 20
19
stdout
ITEM 19 is in the location 6