brain storm
brain storm

Reputation: 31252

unable to find the error in the following method in java

I am a writing a method inside my class called ArrayIntList. This class has two fields, an array of int and int size which indicates the length of array. I am ignoring the constructor here and directly going to the method that I have issues. The method I am trying to write is longestSortedSequence which would return int type of longest sequence of sorted integers in the list. for example, this would return

[1, 3, 5, 2, 9, 7, -3, 0, 42, 308, 17] ---> 4,
[1, 2, 3, 4, 0, 19, 1, 1, 2, 2, 3, 3]----> 6

The code below works for the first case but fails in second case and I am unable to understand why.

public class ArrayIntList {
    private int[] elementData;
    private int size;



public int longestSortedSequence() {
    //this stores the longest sequence possible
    int max_count=0;
    //this stores the counts till not sorted sequence is encountered
    // and is flushed to zero before the next counting begins
    int count=0;
    int i=0;
    while(i<size-1) {
        if (elementData[i]<=elementData[i+1]){
            count++;
        }
        else {
            max_count=Math.max(max_count,count+1);
            count=0;
        }
        i++;
    }
    return max_count;
}

Any help would be much appreciated? Thanks

Upvotes: 0

Views: 141

Answers (2)

voidMainReturn
voidMainReturn

Reputation: 3513

Changed code piece :

    while(i<size-1) {
            if (elementData[i]<=elementData[i+1]){
                count++;
            }
            else {
                max_count=Math.max(max_count,count+1);
                count=0;
            }
            i++;
        }
// added following 1 line.
    max_count=Math.max(max_count,count+1);
        return max_count;

Upvotes: 1

rgettman
rgettman

Reputation: 178253

You only assign max_count if you detect an end of the sequence (the else branch).

If your second example, the longest sequence is at the end (6), but your code never has a chance to assign to max_count.

Move the assignment to max_count out of the else. Then your if will have run already also, so count will have been incremented already, and there will be no need to add 1 to count when comparing to max_count.

Upvotes: 2

Related Questions