Java Number Min Value min(final int a, final int b)

Here you can find the source of min(final int a, final int b)

Description

Provides an unbranched version of min for POSITIVE ints, it does 7 operations instead of branching (which is somewhat slower, but it's mainly here for educational purposes)<br> The original code can be found in: http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax

License

Open Source License

Parameter

Parameter Description
a first value to compare
b second value to compare

Return

the smallest number

Declaration

public static int min(final int a, final int b) 

Method Source Code

//package com.java2s;
/*//from  w  ww  .j  a  v a 2s.co  m
 *                      ..::jDrawingLib::..
 *
 * Copyright (C) Federico Vera 2012 - 2014 <dktcoding [at] gmail>
 *
 * 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Provides an unbranched version of min for POSITIVE ints, it does 7
     * operations instead of branching (which is somewhat slower, but it's
     * mainly here for educational purposes)<br>
     * The original code can be found in:
     * http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
     *
     * @param a first value to compare
     * @param b second value to compare
     * @return the smallest number
     */
    public static int min(final int a, final int b) {
        final int ab = a - b;
        return a & (ab >> 31) | b & (~ab >> 31);
    }
}

Related

  1. min(double x, double y)
  2. min(final float a, final float b)
  3. min(final float a, final float b)
  4. min(final float a, final float b, final float c)
  5. min(final int a, final int b)
  6. min(final Iterable numbers)
  7. min(final NUMBER_TYPE n1, final NUMBER_TYPE n2)
  8. min(final NUMBER_TYPE number1, final NUMBER_TYPE number2)
  9. min(final String string1, final String string2)