# Adding new value in an array to its proper index java

2229 views
9

I have done a little exercise in my book about arrays. The point of the exercise is to add new value to an array if the new value is larger than the smallest. If the new value is larger than the smallest value in the array you have to remove it and add the new value in the array and place it to the right index without fully sorting the array.

``````sample input {54, 21, 2, 5, 8}
newValue = 17
``````

In this case, the output will be `54, 21, 17, 5, 8`

I have done this perfectly, but there is one instance when I got it wrong and when I used the condition `(newVal > arr[j])` instead of `(newVal > arr[j-1])` in the loop where I assign the new value and I am expecting the error will be something like `arrayindexoutofboundsexception` but instead the output is `54, 17, 21, 5, 8` which is incorrect in this case because `17` is smaller than `21`. Can anyone tell me how did this happen?

Following is my code.

``````public static void addNewValue(int[] arr, int newVal) {
//I did not include getMinValue() in this post. It just returns the index
//of the smallest value in the array
int i = getMinValue(arr);
for(; i<arr.length-1; i++) {
arr[i] =  arr[i+1];
}
int j=arr.length-1;
for(; (j>=1) && (newVal > arr[j-1]); j--) {
arr[j] = arr[j-1];
}
arr[j] = newVal;
}
``````

12

What if your minimum value in an array is greater than the size of your array, it will give `arrayindexoutofboundsexception` So you should check all array index and return min value from array along with its index then finally compare it with your new value than only if it is greater than minimum value at array change it like

``````int min=arrayName[0];
int arrayIndex=0;
for(int i =0;i<arrayName.length;i++){
if(min>arrayName[i]){
min=arrayName[i];
arrayIndex=i;
}
}
if(newValue>min){
arrayName[arrayIndex]=newValue;
}
``````

posted this