fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int arr[2000000];
  4. int n ;
  5. // returns the index at which x is present in the arr
  6. // if not returns -1
  7. int binarySearch(int l, int r , int x){
  8. if(l>r)return -1;
  9.  
  10. else {
  11. int mid =(l+r)/2;
  12. if(arr[mid]==x){
  13. return mid;
  14. }
  15. else if(arr[mid]>x){
  16. return binarySearch(l,mid-1, x);
  17. }
  18. else {
  19. return binarySearch(mid+1, r, x);
  20. }
  21. }
  22. }
  23. int main(){
  24. // the length of the array
  25.  
  26. cin>>n;
  27. for(int i=0; i<n; i++){
  28. cin>>arr[i];
  29. }
  30. // if the array was not sorted before
  31. sort(arr, arr+n);
  32.  
  33. // input the element to be searched
  34. int x;
  35. cin>>x;
  36.  
  37. cout<<"x is present at the index "<<binarySearch(0,n-1, x)<<endl;
  38.  
  39. }
  40.  
Success #stdin #stdout 0s 10960KB
stdin
8
1 5 6 8 12 24 36 72
24
stdout
x is present at the index 5