top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Determine element x in an array where each row and column is in ascending order?

+1 vote
265 views

Give an n^2 array of elements such that each row is in ascending order and each column is in ascending order, devise an O(n) algorithm to determine if a given element x in the array.

You may assume all elements in the n^2 array are distinct?

posted Jun 30, 2014 by Joy Dutta

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Try the following algo which I found on http://www.geeksforgeeks.org/
1) Start with top right element
2) Loop: compare this element e with x
....i) if they are equal then return its position
…ii) e < x then move it to down (if out of bound of matrix then break return false)
....iii) e > x then move it to left (if out of bound of matrix then break return false)
3) repeat the i), ii) and iii) till you find element or returned false

int search(int **arr, int n, int x)
{
   int i = 0, j = n-1;  //set indexes for top right element

   while ( i < n && j >= 0 )
   {
      if ( arr[i][j] == x )
      {
         printf("\n Found at %d, %d", i, j);
         return 1;
      }
      if ( arr[i][j] > x )
        j--;
      else //  if arr[i][j] < x
        i++;
   }

   printf("\n Element not found");
   return 0;  
}
answer Jun 30, 2014 by Tapesh Kulkarni
Similar Questions
+3 votes

In an "N" element integer sorted array, a particular elements is repeating "(N/2)+1" times. How much time it take to find the repeating element.

+1 vote

Someone asked me this question and I dont have any answer, so thought to ask?

...