Skip to content
Advertisement

How to count the number of comparisons in this algorithm?

I’m learning to analyze the performance of an algorithm. Here, I have created an algorithm to count the number of capital letters in a sentence. But I don’t understand how to calculate comparisons in an algorithm. Here is my algorithm:

public class CountCapitalLetters{
    public static void main(String[] args) {
        String str = "Wonderfull World";
        char[] capitalLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        int count = 0;
        
        for (int i = 0; i < str.length(); i++) {
            for (int j = 0; j < capitalLetters.length; j++) {
                if (capitalLetters[j] == str.charAt(i))
                    count += 1;
            }
        }
    }
}

And this is the pseudocode:

String str = “Wonderfull World”;
Array capitalLetters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
count = 0
n = length of str
nn = length of capitalLetters

for i = 0 to n
    for j = 0 to nn
        if capitalLetters[j] == str[i]
             count += 1;
        endif
    endfor
endfor

Can someone help me?

Advertisement

Answer

The number of comparisons made is the same as the length of characters of the variable str times 26.

Number of comparisons = str.length() * 26

This is because you are comparing each and every character in str to all the capital letters in the array capitalLetters. Note that I said “character” and not letter, so any spaces in str is also included.

Have a look at this program:

public class Test
{
    public static void main(String[] args) 
    {
        String str = "Wonderfull World" ;
        char[] capitalLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'} ;
        
        int capitalLetterCount = 0 ;
        int comparisonCount = 0 ;

        for (int i = 0; i < str.length(); i++) 
        {
            for (int j = 0; j < capitalLetters.length; j++) 
            {
                if(capitalLetters[j] == str.charAt(i))      // if the letter is a capital letter
                    capitalLetterCount += 1;

                comparisonCount+=1 ;        // as a comparison has been made above
            }
        }

        System.out.println("Number of capital letters: " + capitalLetterCount) ;
        System.out.println("Number of capital comparisons made: " + comparisonCount) ;

        int c = str.length() * 26 ;
        System.out.println(c) ;
    }
}

Every time a comparison is made, the variable comparisonCount is incremented by 1. Run the program and see that both the variables comparisonCount and c have the same values.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement