I have a sorted array and want to recursively find a position for inserting an element. E.g. an array 2,4,5,6,7,8,12,35 with an insertion value of 3 and the algorithm should return the index of the position where the 3 has to be inserted (index 1). The following code works sometimes, and other times it gets stuck in an infinite loop. Eventually my brain feels like jelly and I ask for your help. This is the code:
private static int insertRec(int[] a, int e, int l, int r) {
int mid = l + r / 2;
if (l == r || a[mid] == e) return mid;
if (e > a[mid]) insertRec(a, e, mid + 1, r);
if (e < a[mid]) insertRec(a, e, l, mid - 1);
return -1;
}
Edit with assumed working code:
private static int insertRec(int[] a, int e, int l, int r) {
int mid = (l + r) / 2;
if (l == r || a[mid] == e) return mid;
else if (e > a[mid]) return insertRec(a, e, mid + 1, r);
else if (e < a[mid]) return insertRec(a, e, l, mid - 1);
return -1;
}