Friday, March 29, 2013

Find an element in a sorted 2D array using saddleback search in C

Consider the following sorted 2D array and you want to find an element .
1  2  3
4  6  9
7  8  10

Rows and columns are sorted and assume that its elements are unique . if u want to find an element ,the simplest and easiest approach is to use saddleback search algorithm . This algorithm starts searching from first row last element . If the value is less than the element that you are searching move left otherwise move down . Continue this step until you find the element .

Example.

1) Start from the first row last element(3) .
2) Consider you want to find the element k=8 . It is bigger than 3 , so go down to the second row last element 9.
3) K=8 value is less than 9 . so move left and check boundary condition . Element here is 6 which is less than k . so again move down and check boudary condition .
4) Now the k value is found .

Code:(in C)

Please let me know if you have any questions .

Thursday, March 7, 2013

Program to print last 10 lines of a file in Java

There are two ways to print the last 10 lines of a file.
            1.Go through the file and count the number of lines in that file . Lets say a file contains 100 lines. Read the file again and print the lines from 91 to 100 . Here you need to traverse the file two times .
            2.Create a string array to store the latest 10 lines when you are reading the file and print last 10 lines finally. Second method is given below .

Code : (in JAVA)
Please let me know if you have any questions .