Tuesday, January 3, 2012

Print all elements in sorted order / Search elements from row and column wise sorted matrix

Print a Bidimensional sorted Matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.
Example: Input: mat[][]  =  { {10, 20, 30, 40},
                     {15, 25, 35, 45},
                     {27, 29, 37, 48},
                     {32, 33, 39, 50},
                   };

Output: Elements of matrix in sorted order
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
http://www.geeksforgeeks.org/print-elements-sorted-order-row-column-wise-sorted-matrix/

Search in Bidimensional sorted Matrix
You are provided a n*n square matrix which has elements as both row and column sorted.
Device an algorithm which can search an element in this array within O(n) time.

Example:
There is a bi-dimensional array. All the rows and columns of this array are sorted in ascending order. Example -
3323439
4353840
6565777
45788890

Method 1: Binary Search & Diagonal Binary Search O(nlogn) & O(logn!)
http://articles.leetcode.com/searching-2d-sorted-matrix/

Method 2: Step-wise Linear Search: O(n)
http://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted-matrix/
http://articles.leetcode.com/searching-2d-sorted-matrix-part-ii/
http://www.programcreek.com/2014/04/leetcode-search-a-2d-matrix-ii-java/

Method 3: Quad parition and Binary Partition [ Best Method ]
http://articles.leetcode.com/searching-2d-sorted-matrix-part-ii/
http://articles.leetcode.com/searching-2d-sorted-matrix-part-iii/

Variation:
http://www.programcreek.com/2013/01/leetcode-search-a-2d-matrix-java/

Strategy:
Start from top-right.
  • If search key is lesser than current element, move towards left.
  • If search key is greater, move towards down.
  • Keep doing the same thing until you reach the element.
  • If you reach first column/last row and couldn’t move further, we can conclude the search key is not present in the array.
In worst case, search key will be bottom-left element and will need 2n comparisons. Hence, overall complexity is O(n).

Alternatively,
Imagine that the matrix is sorted in ascending order for both row and column.
Code:
#include<stdio.h>
#include<stdlib.h>
int find(int arr[][5], int size, int num)
{
    int row=size-1;
    int col=0;
    while((row > 0) && (col < size))
    {
        if(arr[row][col] == num)
            return 1;
        else if(arr[row][col] < num)
            col++;
        else
            row--;
    }

    return 0;
}

int main()
{
    int arr[5][5] = {15, 25, 35, 45, 55,
             16, 26, 36, 46, 56,
             17, 27, 37, 47, 57,
             18, 28, 38, 48, 58,
             19, 29, 39, 49, 59};
    int row=0;
    int col=0;
    if(find(arr, 5, 48))
        printf("FOUND!!\n");
    else
        printf("NOT FOUND!!\n");
    getchar();
    return 0;
}

No comments:

Post a Comment