[Solved] Linear Probing. What is wrong with this program?


If you actually debug your code, you’d see that your loop exits prematurely, because 13 iterations won’t do it. Actually, your code cannot give the output you request, as written, no matter how you modify the loop condition.

In order for your result to contain 73, this statement must execute, where j references the last element of inputs:

arr[element] = inputs[j++];

However, if j referenced the last element, then the very next line will fail, because j now exceeds the length of inputs:

element = inputs[j]%13;

So, remove the loop condition, i.e. remove i, then break when j exceeds length of inputs:

int[] arr = new int[13];
int[] inputs = { 18, 41, 22, 44, 59, 32, 31, 73 };
int element = inputs[0] % 13;
for (int j = 0; ; ) {
    if (arr[element] != 0) {
        element++;
        continue;
    }
    arr[element] = inputs[j++];
    if (j == inputs.length)
        break;
    element = inputs[j] % 13;
}
for (int i = 0; i < 13; i++) {
    System.out.print(arr[i] + "  ");
}

Or, better yet, now that you see that dumb for loop, with only an initializer, you’ll realize that your if (...) { ...; continue; } statement is really a while (...) { ... } loop, so you can refactor the code to this, adding an extra guard condition for overflowing the arr array:

int[] arr = new int[13];
int[] inputs = { 18, 41, 22, 44, 59, 32, 31, 73 };
OUTER: for (int i = 0; i < inputs.length; i++) {
    int element = inputs[i] % 13;
    while (arr[element] != 0)
        if (++element == arr.length)
            break OUTER;
    arr[element] = inputs[i];
}
for (int i = 0; i < 13; i++)
    System.out.print(arr[i] + "  ");

solved Linear Probing. What is wrong with this program?