static int insertionSortIndices()

in commons-numbers-arrays/src/main/java/org/apache/commons/numbers/arrays/Sorting.java [509:537]


    static int insertionSortIndices(int[] x, int n) {
        // Index of last unique value
        int unique = 0;
        // Do an insertion sort but only compare the current set of unique values.
        for (int i = 0; ++i < n;) {
            final int v = x[i];
            int j = unique;
            if (v > x[j]) {
                // Insert at end
                x[++unique] = v;
            } else if (v < x[j]) {
                // Find insertion point in the unique indices
                do {
                    --j;
                } while (j >= 0 && v < x[j]);
                // Insertion point = j + 1
                // Insert if at start or non-duplicate
                if (j < 0 || v != x[j]) {
                    // Move (j, unique] to (j+1, unique+1]
                    for (int k = unique; k > j; --k) {
                        x[k + 1] = x[k];
                    }
                    x[j + 1] = v;
                    ++unique;
                }
            }
        }
        return unique + 1;
    }