Andrei Sh Andrei Sh - 1 month ago 7
Java Question

Find an element in the array that is less than M next elements

Task:

Find an element in the array size N is less then M next elements in this array.

Here is algorithm:
a[0]<a[1] => true, then
a[0]<a[2] => false, then
a[2]<a[3] => true, then
a[2]<a[4] => true, then
... => always true
a[2]<a[m+2] => true then return a[2] //a[2] is minumum, m+2<n


My implementation doesn't work. Loop seems to be endless.

int[] array = new int[]{-1, 2, -3, 5, 0, 6, 9, -1, 5, 7, 8, 1};
int numElements = 5;
int i=0;
int j=1;
int result;

while (i+j < array.length){
if (array[i]<array[i+j]){
if (i+j == numElements){
result = array[i];
} else j++;
} else {
i += j;
j = 1;
}
}


My output should be -3.

There is no current output: endless loop.

Answer

When arr[i] < arr[i+j] is false, you should be...

  1. resetting j to 1
  2. setting i equal to i+j

You should also add a check within the while loop condition to ensure i+j < arr.length

Finally~ take j++ out of your else block.

while (i+j < array.length && r){
    if(array[i]<array[i+j]){
        if(i+j == numElements){
            result = array[i];
            r = false;
        }
        ++j;
    }
    else{
        i += j;
        j = 1;
    }
}

When I implemented this in C++, I got the correct output of -3.