Tuesday, February 11, 2014

Program to find element in a sorted matrix

__author__ = 'nitin'

def find_elem_sorted_matrix(mat,M,N,elem):
    row=0
    col=N-1
    while row=0:
        if mat[row][col]==elem:
            return True
        elif mat[row][col]>elem:
            col=col-1
        else:
            row=row+1
    return False

amatrix=[[3,5,8],[6,7,10],[9,11,12]]
rows=len(amatrix)
cols=len(amatrix[0])
print find_elem_sorted_matrix(amatrix,rows,cols,8)

Search an integer in a list with O(logn) complexity if increasingly sorted list rotated n number of times

__author__ = 'nitin'

def rotated_binary_search(alist,item):
    first=0
    last=len(alist)-1
    found=False
    while first<=last:
        mid=(first+last)/2
        if item == alist[mid]:
            return mid
        elif alist[first]<=alist[mid]:
            if item>alist[mid]:
                first=mid+1
            elif item>alist[first]:
                last=mid-1
            else:
                first=mid+1
        elif item            last=mid-1
        elif item<=alist[last]:
            first=mid+1
        else:
            last=mid-1
    return False


alist=[15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14]
print rotated_binary_search(alist,20)

My Profile

My photo
can be reached at 09916017317