/** * This method is the same as binarySearch with the exception that a range * can be given in which shall be searched for the key. * * @param array|\blaze\collections\ArrayI $a * @param mixed $key * @param int $fromIndex The index where to start at in the array * @param int $toIndex The index where to stop at in the array * @param blaze\lang\Comparator $c * @return int * @throws blaze\lang\IndexOutOfBoundsException */ public static function binaryRangeSearch($a, $key, $fromIndex, $toIndex, \blaze\lang\Comparator $c = null) { if (!is_array($a) && !$a instanceof ArrayI) { throw new \blaze\lang\ClassCastException('No array given'); } if ($a->count() == 0) { return 0; } $comparator = true; if ($c == null) { $value = $a[0]; if (is_string($value)) { return \array_search($key, $a); } else { if (is_float($value)) { return \array_search($key, $a); } else { if (is_int($value)) { return \array_search($key, $a); } else { if (is_bool($value)) { return \array_search($key, $a); } else { if ($value instanceof \blaze\lang\Comparable) { $comparator = false; } } } } } throw new IllegalArgumentException('No valid element types!'); } $low = $fromIndex; $high = $toIndex - 1; while ($low <= $high) { $mid = $low + $high >> 1; $midVal = $a[$mid]; if ($comparator) { $cmp = $c->compare($midVal, $key); } else { $cmp = $key->compareTo($midVal); } if ($cmp < 0) { $low = $mid + 1; } else { if ($cmp > 0) { $high = $mid - 1; } else { return $mid; } } // key found } return -($low + 1); // key not found. }
/** * Returns the minimum element of the given collection, according to the natural ordering of its elements. */ public static function min(Collection $src, \blaze\lang\Comparator $comp = null) { if ($src->size() == 0) { return null; } $arr = $src->toArray(); $min = $arr[0]; foreach ($arr as $val) { if ($comp == null && $min->compareTo($val) > 0 || $comp != null && $comp->compare($min, $val) > 0) { $min = $val; } } return $min; }