![JAR search and dependency download from the Maven repository](/logo.png)
com.github.andyshao.arithmetic.ArraySearch Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of Gear Show documentation
Show all versions of Gear Show documentation
Enhance and formating the coding of JDK
The newest version!
package com.github.andyshao.arithmetic;
import com.github.andyshao.lang.ArrayWrapper;
import java.util.Comparator;
/**
*
* Title:
* Descript:
* Copyright: Copryright(c) Mar 3, 2015
* Encoding:UNIX UTF-8
*
* @author Andy.Shao
*
*/
public final class ArraySearch {
/**
* binary search(二分查找)
*
* @param sorted sorted array
* @param target the data which wants to be found out
* @param comparator {@link Comparator}
* @param array type
* @param data type
* @return if can't find out then return -1
*/
public static final int bisearch(ARRAY sorted , DATA target , Comparator comparator) {
final ArrayWrapper arrayWrapper = ArrayWrapper.wrap(sorted);
return ArraySearch.bisearch(arrayWrapper , target , comparator);
}
/**
* binary search
* @param sorted a sorted array
* @param target the data which wants to be found out
* @param comparator {@link Comparator}
* @return if the answer cannot be found out then return -1
* @param data type
*/
@SuppressWarnings("unchecked")
public static final int bisearch(ArrayWrapper sorted , DATA target , Comparator comparator) {
//Continue searching until the left and right indices cross.
int left = 0;
int right = sorted.length() - 1;
while (left <= right) {
int middle = (left + right) / 2;
int compare = comparator.compare((DATA) sorted.get(middle) , target);
//Prepare to search to the right of the middle index.
if (compare < 0) left = middle + 1;
//Prepare to search to the left of the middle index.
else if (compare > 0) right = middle - 1;
//Return the exact index where the data has been found.
else return middle;
}
//Return that the data was not found.
return -1;
}
private ArraySearch() {
throw new AssertionError("No com.github.andyshao.arithmetic.ArraySearch instances for you!");
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy