Find an Element in 2 dimensional sorted array

Objective : Write an algorithm to find an Element in 2 dimensional array where rows and columns are sorted respectively.

Input: A two dimensional sorted array, arrA[][].

Sorted 2D array

 

Output : True or false based on whether element exists and its location

Approach:

  • Start from the right top corner, say ele is the matrix element;
  • If ele>number -> move left
  • If ele<number -> move down
  • If you cant move further to find the number , return false
Find element in Sorted 2D array

Find element in Sorted 2D array

Complete Code:


Output:

The Movement : 4->9->16->15->The 15 present in 2D array a ??? :true
The Movement : 4->9->8->7->6->The 5 present in 2D array a ??? :false
The Movement : 4->9->16->20->19->The 19 present in 2D array a ??? :true
The Movement : 4->9->16->20->The 25 present in 2D array a ??? :false

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: