#interpolation vs #binary #search

in programming •  7 years ago 

Ok guys in this articles i am describing which search works better on sorted data...and we will talk about a bit about time complexity too.

Sources:
(https://en.m.wikipedia.org/wiki/Interpolation_search)
Overview:
#interpolation search: is a search which works parralel like humans to find any indexed key in a particular sorted data.
#binary search: where as binary search always choose middle index and start search with.
#code
#Interpolation search:
def interpolationSearch(arr, n, x):
# Find indexs of two corners
lo = 0
hi = (n - 1)

# Since array is sorted, an element present
# in array must be in range defined by corner
while lo <= hi and x >= arr[lo] and x <= arr[hi]:
    # Probing the position with keeping
    # uniform distribution in mind.
    pos  = lo + int(((float(hi - lo) /
        ( arr[hi] - arr[lo])) * ( x - arr[lo])))

    # Condition of target found
    if arr[pos] == x:
        return pos

    # If x is larger, x is in upper part
    if arr[pos] < x:
        lo = pos + 1;

    # If x is smaller, x is in lower part
    else:
        hi = pos - 1;
 
return -1

Driver Code

Array of items oin which search will be conducted

arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]
n = len(arr)

x = 18 # Element to be searched
index = interpolationSearch(arr, n, x)

if index != -1:
print "Element found at index",index
else:
print "Element not found"

#binary search

Returns index of x in arr if present, else -1

def binarySearch (arr, l, r, x):

# Check base case
if r >= l:

    mid = l + (r - l)/2

    # If element is present at the middle itself
    if arr[mid] == x:
        return mid
     
    # If element is smaller than mid, then it 
    # can only be present in left subarray
    elif arr[mid] > x:
        return binarySearch(arr, l, mid-1, x)

    # Else the element can only be present 
    # in right subarray
    else:
        return binarySearch(arr, mid+1, r, x)

else:
    # Element is not present in the array
    return -1

Test array

arr = [ 2, 3, 4, 10, 40 ]
x = 10

Function call

result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print "Element is present at index %d" % result
else:
print "Element is not present
#time complexity
#binary search :#log(n)+ n log(n) for sorting
#interpolation search #log(log(n)) + nlog(n) for sorting

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
  ·  7 years ago (edited)

I've never had a thing for programming.

  ·  7 years ago Reveal Comment

Thanks guys

Nice insight, been meaning to pick up python again.