Binary Search Implementation In Java

In computer science, a binary search algorithm (or binary chop) is a technique for locating a particular value in a sorted list. The method makes progressively better guesses, and closes in on the location of the sought value by selecting the middle element in the span (which, because the list is in sorted order, is the median value), comparing its value to the target value, and determining if it is greater than, less than, or equal to the target value. A guessed index whose value turns out to be too high becomes the new upper bound of the span, and if its value is too low that index becomes the new lower bound. Only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the difference. Pursuing this strategy iteratively, the method reduces the search span by a factor of two each time, and soon finds the target value or else determines that it is not in the list at all. A binary search is an example of a dichotomic divide and conquer search algorithm. [Source: Wikipedia]

The following code shows how the binary search works. Remember that we have used Comparable Array and Comparable objects.  Comparable objects are nothing but the objects which have implemented java.lang.Comparable interface containing a single method compareTo. This mean for these objects you define a way to compare with one another to find out whether one object is small than, equal to or bigger than the other one.

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 2009-06-16
 */
package com.kushal.utils;

/**
 * A class that shows how to do a binary search on
 * any sorted Comparable Array.
 *
 */
public class BinarySearch {
	public static final int ITEM_NOT_FOUND = -1;

	/**
	 * This method takes an array of comparable objects
	 * and a comparable object to find in the array.
	 * Then it does a Binary Search and returns the index.
	 * Return -1 if the object does not exist in the array.
	 */
	public static int binarySearch(Comparable[] comparableArray, Comparable obj) {
		int lowIndex = 0;
		int highIndex = comparableArray.length - 1;
		int midIndex;

		while (lowIndex <= highIndex) {
			midIndex = (lowIndex + highIndex) / 2;

			if (comparableArray[midIndex].compareTo(obj) < 0)
				lowIndex = midIndex + 1;
			else if (comparableArray[midIndex].compareTo(obj) > 0)
				highIndex = midIndex - 1;
			else
				return midIndex;
		}
		return ITEM_NOT_FOUND;
	}

	/**
	 * Testing the Binary Search Functionality
	 */
	public static void main(String[] args) {
		/**Using Binary Search for Numbers
		 * Array should be a sorted one
		 */
		Comparable[] numbers = new Integer[] { 2, 3, 4, 5, 7, 10 };
		int numberToFind = 3;

		/**Using Binary Search For Strings of Names
		 * Array should be a sorted one.
		 */
		Comparable[] names = { "Anthony", "Brad", "Clooney", "Donald", "Eric" };
		String nameToFind = "Eric";

		/**Finding the location of numberToFind using Binary Search**/
		int numberIndex = binarySearch(numbers, numberToFind);

		/**Finding the location of nameToFind using Binary Search**/
		int nameIndex = binarySearch(names, nameToFind);

		System.out.println(numberToFind + " is available at index: "
				+ numberIndex);
		System.out.println(nameToFind + " is available at index: " + nameIndex);

	}

}

==============================
Here is the sample output for this program:

3 is available at index: 1
Eric is available at index: 4

Simple Implemenation Of Stack In Java Using Vector

Stack is a data structure that works on LIFO (Last In First Out) basis. There are mainly two operations in a stack. The ‘push’ operation places the object at the top of the stack, while the ‘pop’ operation removes the object from the top. We might have additional method like ‘peek’ that does not remove the data but simply returns whatever is there at the top of the stack.

Stack data structure can be implemented in Java using a java.util.vector class. The following code demonstrates how simply you can create a LIFO data structure in Java.

package com.kushal.utils;
import java.util.Vector;

public class MyStack {

	Vector myVector;
	public MyStack()
	{
		myVector=new Vector();
	}

	public void push(Object obj)
	{
		myVector.add(obj);

	}

	public Object pop()
	{
		Object obj=null;
		if(myVector.size()>0)
		{
			obj=myVector.elementAt(myVector.size()-1);
			myVector.removeElementAt(myVector.size()-1);
		}
		else
			System.out.println("Stack Underflow");

		return obj;
	}

	public Object peek()
	{
		Object obj=null;
		if(myVector.size()>0)
			obj=myVector.elementAt(myVector.size()-1);
		else
			System.out.println("Stack Underflow");

		return obj;

	}

}

The following is a test class for testing this custom Stack.

public class MyStackTest{
	public static void main(String args [])
	{
		MyStack stack= new MyStack();

		stack.push(new String("One"));
		System.out.println("Added..>"+stack.peek());
		stack.push(new String("Two"));
		System.out.println("Added..>"+stack.peek());
		stack.push(new String("Three"));
		System.out.println("Added..>"+stack.peek());

		System.out.println();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();

	}
}

Sample output of this program is:

Added..>One
Added..>Two
Added..>Three

The top of stack now is… Three
The top of stack now is… Two
The top of stack now is… One
Stack Underflow
The top of stack now is… null
Stack Underflow

Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting

Chances are you might have needed to convert a list of strings or numbers to a CSV file while you were programming something. An example is that in any java program you might have obtained a list of states of United States stored in your ArrayList object and then you wanted to have them in a CSV format so that you probably could load it to a database or use it for some other purposes.

I wrote this tool to serve the same purpose.

Here are the basic features this simple java example can do. Given a list of String objects stored in an ArrayList, this program can:

  • Convert Strings or numbers stored in an ArrayList object to comma separated strings
  • Print the comma separated values (CSV) to either console or file
  • Optionally you can sort the the list before you do the conversion.

package com.kushal.tools;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author Kushal Paudyal 
 * Last Modified on 2011-09-06 This utility converts a
 * list to comma separated values. Intended to be used with Strings and
 * can be modified with numbers.
 * 
 * Have options to write the converted values to either console or file.
 */
public class ListToCSV {
	private static boolean writeCSVToConsole = true;
	private static boolean writeCSVToFile = true;
	private static String destinationCSVFile = "C:\temp\convertedCSV.csv";
	private static boolean sortTheList = true;

	public static void main(String[] args) {
		ListToCSV util = new ListToCSV();
		List<String> sampleList = util.createSampleList();
		util.convertAndPrint(sampleList, writeCSVToConsole, writeCSVToFile, sortTheList);

	}

	/**
	 * @param sampleList - input list of string
	 * @param writeToConsole - if this flag is true, writes to console
	 * @param writeToFile - if this flag is true writes to file.
	 * @param sortTheList - if the list is to be sorted before conversion
	 */
	private void convertAndPrint(List<String> sampleList,
			boolean writeToConsole, boolean writeToFile, boolean sortTheList) {
		String commaSeparatedValues = "";

		/** If the list is not null and the list size is not zero, do the processing**/
		if (sampleList != null) {
			/** Sort the list if sortTheList was passed as true**/
			if(sortTheList) {
				Collections.sort(sampleList);
			}
			/**Iterate through the list and append comma after each values**/
			Iterator<String> iter = sampleList.iterator();
			while (iter.hasNext()) {
				commaSeparatedValues += iter.next() + ",";
			}
			/**Remove the last comma**/
			if (commaSeparatedValues.endsWith(",")) {
				commaSeparatedValues = commaSeparatedValues.substring(0,
						commaSeparatedValues.lastIndexOf(","));
			}
		}
		/** If writeToConsole flag was passed as true, output to console**/
		if(writeToConsole) {
			System.out.println(commaSeparatedValues);
		}
		/** If writeToFile flag was passed as true, output to File**/		
		if(writeToFile) {
			try {
				FileWriter fstream = new FileWriter(destinationCSVFile, false);
				BufferedWriter out = new BufferedWriter(fstream);
				out.write(commaSeparatedValues);
				out.close();
				System.out.println("*** Also wrote this information to file: " + destinationCSVFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * Creates a sample list to be used by the convertAndPrint method
	 * and returns it to the calling method. 
	 */
	private List<String> createSampleList() {
		List<String> sampleList = new ArrayList<String>();
		sampleList.add("Nebraska");
		sampleList.add("Iowa");
		sampleList.add("Illinois");
		sampleList.add("Idaho");
		return sampleList;
	}
}