Question

In: Computer Science

PYTHON Search for an element in a 2D sorted matrix using the binary search technique. Your...

PYTHON

Search for an element in a 2D sorted matrix using the binary search technique. Your code should run in O(m + n) where m is the number of rows and n is the number of columns
The python file should have a function named binarysearch

The function should take two arguments. The first argument of the function will be the element to search for. Second argument of the function will be the matrix as a List[List].
The function should return the row and column of the matrix if the element is found. Use a tuple to return the row and column. Return "Not Found" if the element is not found.

Sample values for input and output :

Sample Input:
Case 1: binarysearch(4, [[1, 2, 3],[4, 5, 6],[7, 8, 9]] )
Case 2: binarysearch(10,[[2, 3, 4],[5, 7, 9],[11, 12, 13],[20, 22, 24]]

Sample Output :
Case 1: (1 , 0)
Case 2: Not Found

Solutions

Expert Solution

# in row-wise and column-wise sorted matrix
# Searches the element x in mat[][]. If the
# element is found, then return its position
# otherwise returns "not found"
def binarysearch(x,mat):
    i=0
    m=len(mat)

    j=len(mat[0])-1
    l=[]
    t=()
  
    while( i<m and j>=0):
        if(mat[i][j]==x):
            l.append(i)
            l.append(j)
            t=tuple(l)
            return t
      
        if ( mat[i][j] > x):
            j-=1
          
        if mat[i][j] < x:
            i+=1
    return "Not Found"  

# Driver Code
print("1st test case result:")
p=binarysearch(4, [[1, 2, 3],[4, 5, 6],[7, 8, 9]] )
print(p)
print("2nd test case result:")
p=binarysearch(10,[[2, 3, 4],[5, 7, 9],[11, 12, 13],[20, 22, 24]])
print(p)


OUTPUT:-

1st test case result:
(1, 0)
2nd test case result:
Not Found

The above approach complexity is O(m + n).


Related Solutions

inverse a matrix using pseudo inverse using python (numpy can be used) for a 2d list...
inverse a matrix using pseudo inverse using python (numpy can be used) for a 2d list (n x n).
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary...
PYTHON CODING Using the structural node and methods discussed in Binary Search Tree below # Binary Tree Node structure class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None class BSTree(): def __init__(self, rootdata): self.root = Node(rootdata)    def insert(self, data, cur_node): if data < cur_node.data: if cur_node.left == None: cur_node.left = Node(data) else: self.insert(data, cur_node.left)    elif data > cur_node.data: if cur_node.right == None: cur_node.right = Node(data) else:...
(a) Consider the general k-ary search algorithm (generalization of binary search) which splits a sorted array...
(a) Consider the general k-ary search algorithm (generalization of binary search) which splits a sorted array of size n into k subsets each of size n/k and recursively searches only one of these k subsets. Which one of these k subsets should be searched is decided by making (k − 1) comparisons, each of which can be done in constant time. Clearly, the recurrence relation for this k-ary search algorithm can be written as, T(n) = T(n/k) + (k −...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method...
Write a recursive method to implement Binary Search of a sorted integer array. Signature of method could be public int BinarySearch(int target, int low, int high)
Consider the recursive formulation of the Binary Search algorithm. Given a sorted and non-decreasing list of...
Consider the recursive formulation of the Binary Search algorithm. Given a sorted and non-decreasing list of comparable objects L, and a new item x, find the location (index) of x or indicated that x is not in L. 5a) Give a recursive algorithm for binary search. No, while, for, repeat etc statements are allowed. Only if, if else and assignment statements are allowed. 5b) Write a difference equation for the running time of your Binary Search algorithm. Solve your equation...
Given a sorted array with lot of duplicates, write a problem to search specific element m....
Given a sorted array with lot of duplicates, write a problem to search specific element m. If it’s included in the A, return its minimal index, otherwise return -1. For example A = {0, 0, 1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4}, if we search 4, you program should return 8. You are only allowed to use binary search. Linear search is not allowed here.
PYTHON CODING Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary...
PYTHON CODING Create a method (sortTraversal) for a Binary Search Tree that prints out the Binary Search Tree in ascending or deceasing order. The order type is an input to the method and can be "ascending" or "descending". The ascending input would return the node values of the tree beginning with the smallest and ending with the largest, descending returns the opposite. Discuss method's Big-O notation. Add proper and consistent documentation to identify code sections or lines to clearly identify...
develop the Binary search with swap count: Use sorted data from insertion sort (part A) Permutations,...
develop the Binary search with swap count: Use sorted data from insertion sort (part A) Permutations, Insertion Sort – implement algorithms Permutations (Johnson Trotter): {1, 2, 3, 4, 5}; Insertion Sort: {45, 24, 16, 92, 71, 69, 28} develop count of # data “insertions” and develop # of key compares against the following: 16, 77, 24, 92, 44
Draw a single graph in Python showing the performance of both a linear and binary search...
Draw a single graph in Python showing the performance of both a linear and binary search algorithm against the number of elements (100,000). Consider the worst case scenario. In the graph we want to see: labeling of the axes, a legend, a title and the graphs for both linear and binary search, again correctly labeled. Explain what you see. Hint: Use Plot Functions (Plot Chart, series from functions) from the H!de Editor.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT