Google

Sunday, February 22, 2009

Binary Search Algorithm

Over the weekend I read some chapters of Beautiful Code book. It is really interesting and I am seeing the beauty in programming :). I read the Beautiful Test chapter and impressed with the example it has introduced. It is Binary Search algorithm. It says that this algorithm was published in 1946 but took 12 years for the first binary search without bugs to be published. It is amazing!!!
You can refer the most common bug here.

Further it shows that the algorithm may not returns the first position of the target value. But for the binary search algorithm, only pre-condition is to have a sorted array[1]. A sorted array can have duplicate values. If so algorithm should return the first position, as I guess. But the algorithm published in most sites(in wikipedia too) do not consider this point.
Here is the changed algorithm to handle duplicate values,

public static int binarySearch(int[] array, int target){
int low = 0;
int high = array.length - 1;
while(low <= high){
int mid = calculateMidPoint(low, high);
int midValue = array[mid];

if(midValue < target)
low = mid + 1;
else if(midValue > target)
high = mid -1;
else{
while(mid!=0 && target == array[mid-1]) //loop backward to check whether duplicate values present
mid -= 1;
return mid;
}
}
return -1;
}

Here is my java implementation of this algorithm and test classes. My reference is Beautiful Code book.

[1] http://en.wikipedia.org/wiki/Binary_search

Tuesday, February 17, 2009

Limit the number of rows in Oracle and MySql

Say we want to select 10 records for a perticular query, we can use the following syntax

// mysql 

select column from table limit 10;

// Oracle 

select column from table where rownum <= 10;

 

If we want to select number of records from the results set in Oracle,

// Oracle 

select * from (select a.*, rownum rnum from (select column from table) a where rownum <=10) where rnum >= 5;

Thursday, February 12, 2009

Enable wireless on fedora 10

This article guided me to connect to wireless network from fedora 10
http://forums.fedoraforum.org/showthread.php?t=193555

Install vlc player in fedora 10

I installed vlc player in my fedora partition. It consumes time to search plugins for other players like totem.
Use this link to install vlc player using yum
http://www.videolan.org/vlc/download-fedora.html