public static void insertionSort(int[] a) {
for(int i = 1; i < a.length; i++) {
int minVal = a[i];
int checkIdx = i-1;
while(checkIdx >= 0 && minVal < a[checkIdx]) {
a[checkIdx + 1] = a[checkIdx];
checkIdx--;
}
a[checkIdx + 1] = minVal;
}
}
This is my solution for insertion sort iteratively, but what I want is to transform this code recursively. I tried but I got stuck myself in one part.
public static void insertionSort(int[] arr, int i, int n)
{
int value = arr[i];
int j = i;
// Find index j within the sorted subset arr[0..i-1]
// where element arr[i] belongs
while (j > 0 && arr[j - 1] > value)
{
arr[j] = arr[j - 1];
j--;
}
arr[j] = value;
// Note that subarray arr[j..i-1] is shifted to
// the right by one position i.e. arr[j+1..i]
if (i + 1 <= n) {
insertionSort(arr, i + 1, n);
}
}
I got stuck myself in the while loop part, how can I convert it to recursively??