From 51ac425275f41eec76c47b4a2e5f043b4e49d8cc Mon Sep 17 00:00:00 2001 From: mdb Date: Tue, 18 Jun 2002 00:45:18 +0000 Subject: [PATCH] Added binarySearch(). git-svn-id: https://samskivert.googlecode.com/svn/trunk@779 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../samskivert/util/SortableArrayList.java | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java b/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java index e1b2c844..baf65f56 100644 --- a/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java +++ b/projects/samskivert/src/java/com/samskivert/util/SortableArrayList.java @@ -1,5 +1,5 @@ // -// $Id: SortableArrayList.java,v 1.2 2002/02/19 03:53:37 mdb Exp $ +// $Id: SortableArrayList.java,v 1.3 2002/06/18 00:45:18 mdb Exp $ // // samskivert library - useful routines for java programs // Copyright (C) 2001 Michael Bayne @@ -67,6 +67,34 @@ public class SortableArrayList extends AbstractList } } + /** + * Performs a binary search, attempting to locate the specified + * object. The array must be sorted for this to operate correctly and + * the contents of the array must all implement {@link Comparable} + * (and actually be comparable to one another). + * + * @return the index of the object in question or + * (-(insertion point) - 1) (always a negative + * value) if the object was not found in the list. + */ + public int binarySearch (Object key) + { + int low = 0, high = _size-1; + while (low <= high) { + int mid = (low + high) >> 1; + Object midVal = _elements[mid]; + int cmp = ((Comparable)midVal).compareTo(key); + if (cmp < 0) { + low = mid + 1; + } else if (cmp > 0) { + high = mid - 1; + } else { + return mid; // key found + } + } + return -(low + 1); // key not found. + } + // documentation inherited from interface public int size () {