1

I'm trying to implement insertion sort in Java. I think something isn't quite right with my code.

public int[] sort(int[] unsorted) {
    int i, j, v;
    for (i = 1; i < unsorted.length - 1; i++) {
        v = unsorted[i];
        j = i;

        while (unsorted[j-1] > v && j >= 1) {
            unsorted[j] = unsorted[j -1];
            j--;
        }
        unsorted[j] = v;
    }
    return unsorted;
}

I get an IndexOutOfBoundsException for my while loop ([j-1]). But how can I rewrite the code so it actually works?

2
  • 3
    HINT: What happens in your while statement condition when j has just been decremented down to zero? You need to check first if the value of j is "safe" before accessing unsorted[j-1]. Commented Mar 1, 2021 at 13:58
  • as a suggestion, do not call it unsorted. Returning unsorted from a method called sort is misleading, at least. Just source, or similar. Commented Mar 2, 2021 at 0:57

1 Answer 1

2

For index i, you can simply start the index j from i-1. And in the while loop, always put the index validity check first, before accessing data from that index. The following code solves your problem:

public int[] sort(int[] unsorted) {
    int i, j, v;
    for (i = 1; i < unsorted.length; i++) {
        v = unsorted[i];
        j = i - 1;

        while (j >= 0 && unsorted[j] > v) {
            unsorted[j + 1] = unsorted[j];
            j--;
        }
        unsorted[j + 1] = v;
    }
    return unsorted;
}
Sign up to request clarification or add additional context in comments.

3 Comments

it does, no doubts ; )
I agree with you! :) Old habit to say like this.
I do it, too. But better to show security. You solved it, 100%.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.