Big-Oh running time of code in Java (are my answers accurate

Posted by Terry Frederick on Stack Overflow See other posts from Stack Overflow or by Terry Frederick
Published on 2012-10-01T03:36:01Z Indexed on 2012/10/01 3:37 UTC
Read the original article Hit count: 127

Filed under:
|
|

the Method hasTwoTrueValues returns true if at least two values in an array of booleans are true. Provide the Big-Oh running time for all three implementations proposed.

// Version 1

public boolean has TwoTrueValues( boolean [ ] arr ) {
    int count = 0;
    for( int i = 0; i < arr. length; i++ )
        if( arr[ i ] )
            count++;
        return count >= 2;
}

// Version 2

public boolean hasTwoTrueValues( boolean [ ] arr ) {
    for( int i = 0; i < arr.length; i++ )
        for( int j = i + 1; j < arr.length; j++ )
            if( arr[ i ] && arr[ j ] )
                return true;
}

// Version 3

public boolean hasTwoTrueValues( boolean [ ] arr ) {
    for( int i = 0; i < arr.length; i++
        if( arr[ i ] )
            for( int j = i + 1; j < arr.length; j++ )
                if( arr[ j ] )
                    return true;
                        return false;
}

For Version 1 I say the running time is O(n)

Version 2 I say O(n^2)

Version 3 I say O(n^2)

I am really new to this Big Oh Notation so if my answers are incorrect could you please explain and help.

© Stack Overflow or respective owner

Related posts about java

Related posts about big-o