Web Toolbar by Wibiya

Pages

Thursday, July 14, 2011

Given a matrix in which each row and each column is sorted, write a method to find an element in it.

Solution #1: Imagine that the matrix is sorted in ascending order for both row and column. Here is the code,

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;
}

void 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, 24))
        printf("FOUND!!\n");
    else
        printf("NOT FOUND!!\n");

    /*for(row=0; row < 5; row++)
    {
        for(col=0; col < 5; col++)
            printf("%d ", arr[row][col]);

        printf("\n");
    }*/
}

No comments: