Posts

Showing posts from December 14, 2009

split string in java

Java equivalent of PHP explode function In PHP we can easily break a long string into smaller parts by using the   explode()   function of PHP. $longstring="I am a cool guy " ; $brokenstring=explode(" ", $longstring); After the execution of the second command the variable $brokenstring is an array such that, $brokenstring[0]="I" $brokenstring[1]="am" $brokenstring[2]="a" $brokenstring[3]="cool" $brokenstring[4]="guy" In java we use String.split() function that achieves the same objective. class splitString     {         public static void main(String[] args)             {             String s1 = " I am a cool guy ";             String[] array = s1.split(" ");                    for(int i=0; i                 {                 System.out.println(array[i]);                 }             }     }  /* array[0] ="I" array[1] ="am" array[2] ="a&q

binary search in java

Image
Binary Search is the fast way to search a sorted array. The idea is to look at the element in the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half. public class BinarySearch { private long[] a; private int nElems; public BinarySearch(int max) { a = new long[max]; // create array nElems = 0; } public int size() { return nElems; } public int find(long searchKey) { return recFind(searchKey, 0, nElems - 1); } private int recFind(long searchKey, int lowerBound, int upperBound) { int curIn; curIn = (lowerBound + upperBound) / 2; if (a[curIn] == searchKey) return curIn; // found it else if (lowerBound > upperBound) return nElems; // can't find it else // divide range { if (a[curIn] < searchKey) // in upper half return recFind(searchKey, curI