Here you can find the source of addToSortedIntArray(int[] a, int value)
Parameter | Description |
---|---|
a | array to add to, may be null |
value | value to add to a |
public static int[] addToSortedIntArray(int[] a, int value)
//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; } }