Java Array Sort addToSortedIntArray(int[] a, int value)

Here you can find the source of addToSortedIntArray(int[] a, int value)

Description

insert value into the sorted array a, at the index returned by java.util.Arrays.binarySearch()

License

Apache License

Parameter

Parameter Description
a array to add to, may be null
value value to add to a

Return

new sorted array with value added

Declaration

public static int[] addToSortedIntArray(int[] a, int value) 

Method Source Code

//package com.java2s;
/*//  w w  w .  ja  va  2s  . c  om
 *  Copyright Gergely Nagy <greg@webhejj.hu>
 *
 *  Licensed under the Apache License, Version 2.0; 
 *  you may obtain a copy of the License at:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 */

public class Main {
    /**
     * insert value into the sorted array a, at the index returned by java.util.Arrays.binarySearch()
     * @param a array to add to, may be null
     * @param value value to add to a
     * @return new sorted array with value added
     */
    public static int[] addToSortedIntArray(int[] a, int value) {

        if (a == null || a.length == 0) {
            return new int[] { value };
        }

        int insertionPoint = -java.util.Arrays.binarySearch(a, value) - 1;
        if (insertionPoint < 0) {
            throw new IllegalArgumentException(String.format("Element %d already exists in array", value));
        }

        int[] array = new int[a.length + 1];
        if (insertionPoint > 0) {
            System.arraycopy(a, 0, array, 0, insertionPoint);
        }
        array[insertionPoint] = value;
        if (insertionPoint < a.length) {
            System.arraycopy(a, insertionPoint, array, insertionPoint + 1, array.length - insertionPoint - 1);
        }

        return array;
    }
}

Related

  1. addSorted(int[] array, int[] newValues)
  2. addSortedUnique(T[] array, T object, int start)
  3. bitReversalSort(final short[] real)
  4. calculatePValueForDataPoint(double dataPoint, double[] sortedNullHypothesisSample)
  5. collectionToSortedArray(Collection objects)
  6. copyAndSort(String[] input)