Binary search divide &conqur


Algorithm:

Algorithm BinSrch(a, i, I, a:) if (l=i) then

{

{

if (x =a[i]) then return i; else return 0;

else

}

{

mid := [(i+l)/2J;

if (x = a[mid]) then return mid; else if (x < a[midJ) then

return BinSrch(a, i, mid — 1, x); else return BinSrch(a, mid + 1,l,x);

}

}

 

Source Code:

def bin_search(a, i, l, x): if l == i:

if x == a[i]:

return i else:

return "Not Found"

else:

mid = (i+l) // 2 if x == a[mid]:

return mid elif x < a[mid]:

return bin_search(a, i, mid-1, x) else:

return bin_search(a, mid+1, l, x)

 

arr=[1,2,3,4,5,6,7,8,9]

num=int(input("Enter a number to search: ")) print("Index",bin_search(arr,0,8,num))




 

Comments

Popular posts from this blog

2. Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.

Kruskal algorithm using greedy technique.