NetBeans Java Tutorial – Binary Search #4

In this tutorial I show how to implement a binary search algorithm in Java.

Code:

package tutorials;
 
import java.util.ArrayList;
 
/**
 *
 * @author Edward
 */
public class Searches {
	public static void main(String[] args) {
		Searches searches = new Searches();
		searches.testBinarySearch();
	}
 
	public void testBinarySearch() {
		System.out.println(binarySearch(this.generateOrderedArray(), 640));
	}
 
	private int binarySearch(int[] array, int toFind) {
		int low = 0;
		int high = array.length - 1;
		int mid = 0;
 
		while (low <= high) {
			mid = (int) Math.floor((low + high) / 2);
			int element = array[mid];
 
			if (toFind == element) {
				return mid;
			} else if (toFind < element) {
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		return -1;
	}
 
	private int[] generateOrderedArray() {
		int[] array = new int[100];
 
		for (int i = 0; i <= 99; i++) {
			array[i] = i * 10;
		}
		return array;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *