Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Find an Element in 2 dimensional sorted array

Objec­tive : Write an algo­rithm to find an Ele­ment in 2 dimen­sional array where rows and columns are sorted respectively.

Input: A two dimen­sional sorted array, arrA[][].

Sorted 2D array

Sorted 2D array

 

Out­put : True or false based on whether ele­ment exists and its location

Approach:

  • Start from the right top cor­ner, say ele is the matrix element;
  • If ele>num­ber -> move left
  • If ele<num­ber -> move down
  • If you cant move fur­ther to find the num­ber , return false
Find element in Sorted 2D array

Find ele­ment in Sorted 2D array

Com­plete Code:

Out­put:

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

You may also like...