All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.psjava.algo.sequence.search.BinarySearchFirst Maven / Gradle / Ivy

There is a newer version: 0.1.19
Show newest version
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;
	}

}