fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int rotated_search(vector<int>arr,int target){
  6. int n=arr.size();
  7. int low=0;
  8. int high=n-1;
  9.  
  10. while(low<=high){
  11. int mid=(low+high)/2;
  12. if(arr[mid]==target){
  13. return mid;
  14. }
  15.  
  16. else if(arr[low]<=arr[mid]){
  17. if(arr[mid]>target && target>=arr[low]){
  18. high=mid-1;
  19. }
  20. else{
  21. low=mid+1;
  22. }
  23. }
  24. else{
  25. if(arr[mid]<target && target<=arr[high]){
  26. low=mid+1;
  27. }
  28. else{
  29. high=mid-1;
  30. }
  31. }
  32.  
  33. }
  34.  
  35. return -1;
  36.  
  37.  
  38. }
  39. int main(){
  40. int n;
  41. cin>>n;
  42. vector<int>arr(n);
  43. for(int i=0;i<n;i++){
  44. cin>>arr[i];
  45. }
  46. int target;
  47. cin>>target;
  48. int ans=rotated_search(arr,target);
  49. cout<<"The index of the given target element in the rotated array: "<<ans<<endl;
  50. return 0;
  51. }
Success #stdin #stdout 0s 5320KB
stdin
8
5 6 7 8 1 2 3 4
2
stdout
The index of the given target element in the rotated array: 5