private static void doSelect()

in commons-numbers-arrays/src/main/java/org/apache/commons/numbers/arrays/Selection.java [202:242]


    private static void doSelect(double[] a, int fromIndex, int toIndex, int k) {
        if (toIndex - fromIndex <= 1) {
            return;
        }
        // Sort NaN / count signed zeros.
        // Caution: This loop contributes significantly to the runtime.
        int cn = 0;
        int end = toIndex;
        for (int i = toIndex; --i >= fromIndex;) {
            final double v = a[i];
            // Count negative zeros using a sign bit check
            if (Double.doubleToRawLongBits(v) == Long.MIN_VALUE) {
                cn++;
                // Change to positive zero.
                // Data must be repaired after selection.
                a[i] = 0.0;
            } else if (v != v) {
                // Move NaN to end
                a[i] = a[--end];
                a[end] = v;
            }
        }

        // Partition
        if (end - fromIndex > 1 && k < end) {
            QuickSelect.select(a, fromIndex, end - 1, k);
        }

        // Restore signed zeros
        if (cn != 0) {
            // Use partition index below zero to fast-forward to zero as much as possible
            for (int j = a[k] < 0 ? k : -1;;) {
                if (a[++j] == 0) {
                    a[j] = -0.0;
                    if (--cn == 0) {
                        break;
                    }
                }
            }
        }
    }