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

Java Code Implementation Of Selection Sort

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n^2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.

The algorithm works as follows:

1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)

Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Selection sort can also be used on list structures that make add and remove efficient, such as a linked list. In this case it’s more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far.

Variants of Selection Sort:
Heapsort greatly improves the basic algorithm by using an implicit heap data structure to speed up finding and removing the lowest datum. If implemented correctly, the heap will allow finding the next lowest element in T(log n) time instead of T(n) for the inner loop in normal selection sort, reducing the total running time to T(n log n).

A bidirectional variant of selection sort, called cocktail sort, is an algorithm which finds both the minimum and maximum values in the list in every pass. This reduces the number of scans of the list by a factor of 2, eliminating some loop overhead but not actually decreasing the number of comparisons or swaps. Note, however, that cocktail sort more often refers to a bidirectional variant of bubble sort.

Selection sort can be implemented as a stable sort. If, rather than swapping in step 2, the minimum value is inserted into the first position (that is, all intervening items moved down), the algorithm is stable. However, this modification either requires a data structure that supports efficient insertions or deletions, such as a linked list, or it leads to performing T(n^2) writes. Either way, it eliminates the main advantage of insertion sort (which is always stable) over selection sort.

In the bingo sort variant, items are ordered by repeatedly looking through the remaining items to find the greatest value and moving all items with that value to their final location. Like counting sort, this is an efficient variant if there are many duplicate values. Indeed, selection sort does one pass through the remaining items for each item moved. Bingo sort does two passes for each value (not item): one pass to find the next biggest value, and one pass to move every item with that value to its final location. Thus if on average there are more than two items with each value, bingo sort may be faster.

(Source Of The Above Text: Wikipedia
Text is available under the Creative Commons Attribution/Share-Alike License)
———————————-

The following is my implementation of Selection Sort in Java.