```001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
010 *
011 * Unless required by applicable law or agreed to in writing, software
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math4.legacy.stat.descriptive.rank;
018
019import org.apache.commons.math4.legacy.core.MathArrays;
020
021/**
022 * Classic median of 3 strategy given begin and end indices.
023 * @since 3.4
024 */
025public class MedianOf3PivotingStrategy implements PivotingStrategy {
026    /**{@inheritDoc}
027     * This in specific makes use of median of 3 pivoting.
028     * @return The index corresponding to a pivot chosen between the
029     * first, middle and the last indices of the array slice
030     * @throws org.apache.commons.math4.legacy.exception.MathIllegalArgumentException MathIllegalArgumentException when indices exceeds range
031     */
032    @Override
033    public int pivotIndex(final double[] work, final int begin, final int end) {
034        MathArrays.verifyValues(work, begin, end - begin);
035        final int inclusiveEnd = end - 1;
036        final int middle = begin + (inclusiveEnd - begin) / 2;
037        final double wBegin = work[begin];
038        final double wMiddle = work[middle];
039        final double wEnd = work[inclusiveEnd];
040
041        if (wBegin < wMiddle) {
042            if (wMiddle < wEnd) {
043                return middle;
044            } else {
045                return wBegin < wEnd ? inclusiveEnd : begin;
046            }
047        } else {
048            if (wBegin < wEnd) {
049                return begin;
050            } else {
051                return wMiddle < wEnd ? inclusiveEnd : middle;
052            }
053        }
054    }
055}

```