I am trying to write a method that takes a sorted array and an integer, creates a new array of size 1 size and inserts a new integer and keeps it sorted.
I tried several different implementations and made them work, but for this particular I can not understand where this is happening.
int[] array1 = new int[]{1, 2, 3, 4, 6, 7, 8};
int[] printArray = insert(array1, 5);
are arrays, and the method
public static int[] insert(int[] a, int k) {
int[] s = new int[a.length + 1];
for(int i = 0; i < a.length; i++) {
if(k < s[i]) {
s[i] = k;
for(int j = i + 1; j < s.length; j++) {
s[j] = a[i];
i++;
}
return s;
} else {
s[i] = a[i];
}
}
return s;
}
This method returns 1, 2, 3, 4, 6, 7, 8, 0 instead of 1, 2, 3, 4, 5, 6, 7, 8.
source
share