[Solved] Insertion sort using recursive algorithm in Java (no loops)


I assume you start your recursion (eg) like this:

    int[] values = new int[] {7, 9, 1, 8, 2};
    IS(values, 0);

If you print the output you see that your solution is reaching the solution, but it is not quite there yet. Output for this example: 7, 1, 8, 2, 9. Effectively, the only thing that has happened is that the 9 has shifted to the right a few times.

More shifting is needed. You can do that by calling IS several times. This is dead-ugly from a performance perspective, but it works:

public void metaIS(int[] a, int i) {
    IS(a, 0);
    if (i < a.length) {
        metaIS(a, i + 1);
    }
}

That is, call IS 5 times if the array is 5 numbers long, and all is good: 1, 2, 7, 8, 9

By the way, it might be a good idea to rename the method. When people hear IS, recursive problem solving is not the first thing that comes to their minds. And a common convention is to start method names with non-capitals.

solved Insertion sort using recursive algorithm in Java (no loops)