I am trying to write a method that takes a sorted array and an integer, and returns a new sorted array with the integer in the correct place.
I am trying to do this without using dynamic arrays, as well as only using 1 for loop - I have this working using a different method.
This is the method :
public static int[] insert(int[] a, int k) {
int j = 0;
int[] s = new int[a.length + 1];
for(int i = 0; i < a.length; i++) {
if(k < a[i] && j == 0) {
s[i] = k;
j++;
} else {
s[i + j] = a[i];
}
}
return s;
}
My test input is
int[] array1 = new int[]{1, 2, 3, 4, 6, 7, 8};
and I am trying to insert a 5.
The issue I am having with this particular method is that it will always set the index after the inserted integer to 0. In this case it would store and print
1, 2, 3, 4, 5, 0, 7, 8
rather than
1, 2, 3, 4, 5, 6, 7, 8
Thanks
array1? and inserting 5 which is already present in yourarray1.Arraysthat could helps[i + j]=a[i];inside yourifafterj++to copy the value at inserted position . or simply removeelsepart