Java Number Max Value max(final int a, final int b)

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

Description

Provides an unbranched version of max for POSITIVE ints, it does 7 operation 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 biggest number

Declaration

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

Method Source Code

//package com.java2s;
/*//  w  w  w .j  ava 2s.  c  o 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 max for POSITIVE ints, it does 7
     * operation 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 biggest number
     */
    public static int max(final int a, final int b) {
        final int ab = a - b;
        return b & (ab >> 31) | a & (~ab >> 31);
    }
}

Related

  1. max(final double a, final double b, final double c)
  2. max(final float a, final float b)
  3. max(final float a, final float b)
  4. max(final float a, final float b, final float c)
  5. max(final int a, final int b)
  6. max(final Iterable numbers)
  7. max(final Iterable values)
  8. max(final NUMBER_TYPE n1, final NUMBER_TYPE n2)
  9. max(final NUMBER_TYPE number1, final NUMBER_TYPE number2)