My program is trying to find the longest contiguous sequence of an array, but the output is wrong.
public class longsec {
public int[] longestForward(int[] arr){
int subSeqLength = 1;
int longest = 1;
int indexStart = 0;
int indexEnd = 0;
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] == arr[i + 1] - 1)
{
subSeqLength++;
if (subSeqLength > longest)
{
longest = subSeqLength;
indexStart = i + 2 - subSeqLength;
indexEnd = i + 2;
}
}
else
subSeqLength = 1;
}
int T[] = new int[arr.length];
for (int i = indexStart; i < indexEnd; i++)
T[i]= arr[i];
return T;
}}
The reason why that is happening is because you are creating an array with the same size as the array you inputted. As you can see here.
int T[] = new int[arr.length];
However if just change that piece of code you will get an arrayIndexOutOfBoundsException. And it will be thrown here:
for (int i = indexStart; i < indexEnd; i++) T[i]= arr[i];
Because indexStart will ussually be greater than the length of the array. So instead of looping from indexStart to indexEnd what you should be doing is looping through the length of the contiguous numbers like this.
int T[] = new int[longest]; for(int i = 0; i < longest; i++) T[i] = arr[i + indexStart];
That should give you your desired output. What I am doing is just offsetting the iteration by the indexStart value of your array.