I need to search for an element in a sorted and pivoted array (array may contain repeated elements). Sorted and pivoted array means a sorted array is rotated by k elements.
int sortedpivot( int arr[], int start , int end , int x)
{
if ( start > end ) return -1;
if ( start == end ) return x== arr[start]? start : -1;
int mid = ( end - start ) /2 + start ;
if ( arr[ mid] == x) return mid;
if ( arr[ mid] > arr[ start])
{
if ( x< arr[ mid] && x>= arr[ start])
return sortedpivot( arr, start , mid-1, x);
else
return sortedpivot( arr, mid + 1, end , x);
}
else
{
if ( x> arr[ mid] && x<= arr[ end])
return sortedpivot( arr, mid+1, end, x);
else
return sortedpivot( arr, start, mid-1 , x);
}
}
The above code fails in array with repeated elements. Can anyone suggest improvements?
One possible answer could be..
1) First find the minimum element and make it in sorted order.
Complexity : worst-case O(n)
2) Search desired element by binary search.
Complexity : log(n)
The below python code does the rotation of array and search for the element using binary search
import random
def rotate(a):
n = len(a)
tmp = a[n-1]
for i in range(N-2,-1, -1):
a[i+1]=a[i]
a[0] = tmp
def rotate_multi(a,t):
if t > len(a):
return
for i in range(t):
rotate(a)
def binary_search(a,l,h,item):
if l > h:
return -1
m = (l+h)//2
if a[m] == item:
return m
elif a[m] > item:
return binary_search(a,l,m-1,item)
else:
return binary_search(a,m+1,h,item)
def find(a,item):
pos = 0
for i in range(len(a)-1):
if a[i] > a[i+1]:
pos = i
break
if a[pos] == item:
return pos
elif item > a[len(a)-1]:
return binary_search(a,0,pos,item)
else:
return binary_search(a,pos+1,len(a)-1,item)
if __name__=="__main__":
print("Python program for Array rotation and binary search")
N = int(input("How many numbers?"))
a = random.sample(range(1,1000), N)
print("The input numbers are")
a.sort()
print(a)
r = random.randint(1,N)
rotate_multi(a,r)
print("The input numbers after %d rototations" %r)
print(a)
item= int(input("Enter the number to search ?"))
pos = find(a,item)
if pos == -1:
print("The number %d not found in the array " %item)
else:
print("The number %d found at the position in the array at postition %d" %(item, pos+1))
output:
Python program for Array rotation and binary search
How many numbers?10
The input numbers are
[108, 351, 426, 492, 551, 563, 617, 687, 720, 780]
The input numbers after 7 rototations
[492, 551, 563, 617, 687, 720, 780, 108, 351, 426]
Enter the number to search ?720
The number 720 found at the position in the array at postition 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.