org.psjava.algo.sequence.search.BinarySearchFirst Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of psjava Show documentation
Show all versions of psjava Show documentation
Problem Solving Library for Java
package org.psjava.algo.sequence.search;
import java.util.Comparator;
import org.psjava.ds.math.Function;
import org.psjava.ds.numbersystrem.IntegerDivisableNumberSystem;
import org.psjava.formula.FloorDivide;
public class BinarySearchFirst {
public static I search(IntegerDivisableNumberSystem inputNumberSystem, Function f, Comparator sortedOrder, I begin, I end, O target, I def) {
I r = searchFirstPositionCanBeInserted(inputNumberSystem, begin, end, target, f, sortedOrder);
if (!r.equals(end) && f.get(r).equals(target))
return r;
else
return def;
}
private static I searchFirstPositionCanBeInserted(IntegerDivisableNumberSystem ns, I begin, I end, O value, Function f, Comparator sortedOrder) {
I one = ns.getOne();
I two = ns.add(one, one);
while (ns.compare(begin, end) < 0) {
I midKey = FloorDivide.calc(ns, ns.add(begin, end), two);
O midValue = f.get(midKey);
if (sortedOrder.compare(midValue, value) < 0)
begin = ns.add(midKey, one);
else
end = midKey;
}
return end;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy