Write a python program to perform linerSearch And binary search on two dimensional (2D) array.


Perform linerSearch And binary search on the middle column till only two elements are left or till the middle element of some row in the search is the required element 'x'. This search is done to skip the rows that are not required The two left elements must be adjacent. Consider the rows of two elements and do following check whether the element 'x' equals to the middle element of any one of the 2 rows otherwise according to the value of the element 'x' check whether it is present in the 1st half of 1st row, 2nd half of 1st row, 1st half of 2nd row or 2nd half of 2nd row.


code of linerSearch And binary search on two dimensional (2D) array in python


def linerSearch(arr, matrix, row, col, key):
pos = -1
flag = 0
for i in range(row):
for j in range(col):
if(matrix[i][j] == key):
flag = 1
pos = i, j
break
if flag == 1:
return flag, pos
else:
return flag, pos
if flag == 1:
return flag, pos
else:
return flag, pos
matrix = []
row = int(input("Enter Size of row : "))
col = int(input("Enter Size of columns : "))
for i in range(row):
arr = []
for j in range(col):
arr.append(int(input()))
matrix.append(arr)
for i in range(row):
for j in range(col):
print(matrix[i][j], end=" ")
print()
key = int(input("Enter number for Search : "))
flag, pos = linerSearch(arr, matrix, row, col, key)
if flag == 1:
print(" Value is find ")
else:
print(" Value is not found ")

Code Link

Output :

Enter Size of row : 3
Enter Size of columns : 3
1
2
3

4
5
6

7
8
9

1 2 3
4 5 6
7 8 9
Code Link 1
Code Link 2
Code Link 3
Code Link 4

design by MonkOp