Created
July 1, 2016 07:41
-
-
Save 5hirish/b7b66126ea87f673dff29294d4778c59 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
def search_func(initial, terminal, search_val, elements, position) : | |
# print (initial," to ",terminal) | |
difference = terminal - initial | |
#print "Diff :" , position + difference | |
elements = elements[initial:terminal] | |
length = len(elements) | |
if length > 1 : | |
print "Searching at: ",elements | |
mid = length/2 | |
#print("Mid position", mid) | |
if mid > 0: | |
element_mid = elements[mid] | |
print "Middle element: ", element_mid | |
if element_mid == search_val : | |
print "Element found at the middle ", search_val ," at ",position | |
elif element_mid > search_val : | |
print "" | |
print("Searching Left...") | |
position = position - mid | |
initial = 0 | |
search_func(initial, mid, search_val, elements, position) | |
elif element_mid < search_val : | |
print "" | |
print("Searching Right...") | |
position = position + mid | |
search_func(mid + 1, length, search_val, elements, position) | |
else : | |
print "Not Found" | |
elif length > 0 and elements[length - 1] == search_val : | |
print "Element found: ", search_val, " at ", position | |
else : | |
print "Element not found...!", search_val | |
##################################################################################### | |
elements = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200] | |
"""elements = [] | |
for x in xrange(0,5): | |
prompt = "Enter the element at " + str(x) +": " | |
val = input(prompt) | |
elements.append(val)""" | |
length = len(elements) | |
position = 0 | |
print "Your list" ,elements,"\n" | |
search_val = input("Enter the element to search:") | |
print "" | |
if length > 1: | |
mid = length/2 | |
position = mid | |
element_mid = elements[mid] | |
print "Middle element: ", element_mid | |
if element_mid == search_val : | |
print "Element found at the middle: ", search_val, " at ", position | |
elif element_mid > search_val : | |
print "" | |
print("Searching Left...") | |
initial = 0 | |
search_func(initial, mid, search_val, elements, position) | |
elif element_mid < search_val : | |
print "" | |
print("Searching Right...") | |
search_func(mid + 1, length, search_val, elements, position) | |
else : | |
print "Not Found" | |
elif length > 0 and elements[length - 1] == search_val : | |
print "Element found: ", search_val, " at ",position | |
else : | |
print "Element not found...!", search_val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment