Download code

Jump to: navigation, search

Back to Binary_search_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

BinarySearch.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Binary_search_(Java)?oldid=19020
14 */
15 
16 
17 import static org.junit.Assert.assertEquals;
18 import org.junit.Test;
19 
20 import java.util.Arrays;
21 import java.util.List;
22 
23 public class BinarySearch {
24 	static <T extends Comparable<? super T>> int search(T value, List<T> values) {
25 		int n = values.size();
26 		int mid, left, right;
27 		T midVal;
28 		left = 0;
29 		right = n - 1;
30 		
31 		do {
32 		    mid = (left + right) / 2;
33 		    midVal = values.get(mid);
34 		    if (value.compareTo(values.get(mid)) < 0)
35 		        right = mid - 1;
36 		    else if (value.compareTo(values.get(mid)) > 0)
37 		        left = mid + 1;
38 		    else
39 		        return mid;
40 		} while (left <= right);
41 
42 		
43 		return (value.compareTo(midVal) < 0) ? -mid : -(mid + 1);
44 	}
45 	@Test
46 	public void testStringSearch() {
47 		
48 		assertEquals(-1, BinarySearch.search("Billy", Arrays.asList("Anny","Emmy","Grammy")));
49 	}
50 	
51 	@Test
52 	public void testIntegerSearch() {
53 		
54 		assertEquals(-1, BinarySearch.search(2, Arrays.asList(1, 3, 4)));
55 	}
56 }


hijacker
hijacker
hijacker
hijacker