I am trying to get my head around Python having only really ever coded in Java in the past. I need some help understanding some code if someone can help, or point me in the direction of a good (simple) resource please?
I have written a Binary sort in Python from some pseudocode, it works but I don't understand how. The function would make sense to me if the code below didn't have a return statement on the line:
return findData( data, criteria, first, mid -1 )
Or if I set up a while loop and just modified the start or end index variable based on which half of the list I needed to reference.
But with this code I don't understand where the function is being returned to, or why the code fails if i remove them?? It makes sense that I return -1 as no match and 'mid' to reference the list position of a match, but the return statement passing data, criteria, first and last should surly cause a syntax error as there is no call to such a function?
Thanks in advance to anyone who can explain how what I have written works. My code is below.
Mr.D
# Binary Search
def findData( data, criteria, first, last ):
if( last < first ):
return -1
else:
mid = ( last + first ) // 2
if( criteria == data[mid] ):
return mid
elif ( criteria > data[mid] ):
print( "Currently looking at", data[mid], "in array poition", mid )
return findData( data, criteria, mid +1, last )
elif( criteria < data[mid] ):
print( "Currently looking at", data[mid], "in array poition", mid )
return findData( data, criteria, first, mid -1 )
Data = [15, 21, 29, 32, 37, 40, 42, 43, 48, 50, 60, 64, 77, 81, 90, 98]
Criteria = 98
Location = -1
Location = findData( Data, Criteria, 0, len( Data ) -1 )
if( Location < 0 ):
print( Criteria, "is not located in the array." )
else:
print( Criteria, "is located in array position ", Location )