Method-1
def cei(a,i,j,x):
if x <= a[i]:
return i
if x > a[j]:
return -1
mid = (i+ j)/2;
if a[mid] == x:
return mid
elif a[mid] < x:
if mid + 1 <= j and x <= a[mid+1]:
return mid + 1
else:
return cei(a, mid+1,j, x)
else:
if mid - 1 >= i and x > a[mid-1]:
return mid
else:
return cei(a, i, j - 1, x)
if x >= a[i]:
return j
if i >j:
return -1
mid = (i+ j)/2;
if a[mid] == x:
return mid
elif x<a[mid] :
if mid + 1 <= j and x <= a[mid+1]:
return mid + 1
else:
return cei(a, mid+1,j, x)
else:
if mid - 1 >= i and x > a[mid-1]:
return mid
else:
return cei(a, i, j - 1, x)
a=list(map(int,input().split()))
x=int(input())
i=0
j= len(a)-1
ind= cei(a,0,j, x);
if ind == -1:
print ("Ceiling of %d doesn't exist in array "% x)
else:
print ("ceiling of %d is %d"%(x, a[ind]))
Method-2
def cei(a,i,j,x):
if x<a[i]:
return i
for k in range(j):
if a[k]==x:
return k
if a[k]<x and a[k+1]>=x:
return k+1
return -1
a=list(map(int,input().split()))
x=int(input())
i=0
j= len(a)-1
ind= cei(a,0,j, x);
if ind == -1:
print ("Ceiling of %d doesn't exist in array "% x)
else:
print ("ceiling of %d is %d"%(x, a[ind]))
input:
1 2 8 10 12 15
9
Output
ceiling of 9 is 10
No comments:
Post a Comment