In the above statement (s+e)>>1 , what does >> in this case ?
shouldn’t mid be ‘mid = (s+e)/2’ ?
Int mid=(s+e)>>1; (meaning of right shift)
hi @jayasmit98, >> is a binary operator called as right shift operator
>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.Similarly right shifting (x>>y) is equivalent to dividing x with 2^y.
for eg if we have 9 which has binary representation as 1001 if we do 9>>1 that means shift one bit rightward thus we get 0100 as output which formulates to 4 which is also (9/2). similarly doing 9>>2 will result in 0010 that is 2 which is also (9/2^2).
so doing (s+e)>>1 will result same value as (s+e)/2.
why we did this ?
because binary operations(&,|,>>,<<,~) are faster than airthmetic operations (+,/,*,-)
In case of any doubt feel free to ask
mark your doubt as resolved if you got the answer
Super explanation
can i ask querry any time.
QUE. Search in Rotated Sorted Array.
There is an integer array nums
sorted in ascending order (with distinct values).
Prior to being passed to your function, nums
is possibly rotated at an unknown pivot index k
( 1 <= k < nums.length
) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
( 0-indexed ). For example, [0,1,2,4,5,6,7]
might be rotated at pivot index 3
and become [4,5,6,7,0,1,2]
.
Given the array nums
after the possible rotation and an integer target
, return the index of target
if it is in nums
, or -1
if it is not in nums
.
You must write an algorithm with O(log n)
runtime complexity.
CODE
int getpivot(vector& nums,int n) {
int s=0;
int e=n-1;
while(s<e){
int mid=s+(e-s)/2;
if(nums[mid]>=nums[0]){
s=mid+1;
}else{
e=mid;
}
mid=s+(e-s)/2;
}return s;
}
int binarysearch(vector<int>& nums, int s,int e,int target)
{
int start=s;
int end=e;
int mid=start+(end-start)/2;
while(start<=end){
if(nums[start]==target){
return s;
}else
if(nums[mid]==target){
return mid;
}
//go to right wala part
if(target>nums[mid]){
s=mid-1;
}else{//key <arr[mid]
e=mid-1;
}
mid=s+(e-s)/2;
}
return -1;
}
int search(vector<int>& nums, int target) {
int n=nums.size();
int pivot=getpivot(nums,n);
if(target>=nums[pivot]&& target<=nums[n-1]){
return binarysearch(nums,pivot,n-1,target);
}
else{
return binarysearch(nums,0,pivot,target);
}
}
};
is code me TLE bta rha h bhaiya
i unable to understand