Java tutorial
//package com.java2s; /* * Copyright (C) 2012 Davide Mottin <mottin@disi.unitn.eu> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.util.Comparator; import java.util.List; public class Main { /** * * @param <T> * @param list * @param element * @param c * @return the position of the element if present, -1 otherwise */ public static <T extends Comparable<? super T>> int binarySearchOf(List<T> list, T element, Comparator<? super T> c) { return binarySearchOf(list, element, 0, list.size(), c); } /** * * @param <T> * @param list * @param element * @return the position of the element if present, -1 otherwise */ public static <T extends Comparable<? super T>> int binarySearchOf(List<T> list, T element) { return binarySearchOf(list, element, 0, list.size(), null); } /** * * @param <T> * @param list * @param element * @param start * @param end * @param c * @return the position of the element if present, -1 otherwise */ public static <T extends Comparable<? super T>> int binarySearchOf(List<T> list, T element, int start, int end, Comparator<? super T> c) { int mid = (start + end) / 2; if (start > end || mid >= end) { return -1; } int compared = -1; try { compared = c == null ? list.get(mid).compareTo(element) : c.compare(list.get(mid), element); } catch (Exception e) { throw new IllegalStateException( "Exception while searching for " + element + " from " + start + " to " + end, e); } if (compared == 0) { return mid; } else if (compared < 0) { return binarySearchOf(list, element, mid + 1, end, c); } else { return binarySearchOf(list, element, start, mid, c); } } }