简体   繁体   中英

Evaluating the time efficiency of KMP algorithm on list of objects

I implemented KMP pattern searching algorithm in my program to search through a table of objects. I was wondering how I could evaluate the time efficiency of my function.

I read some sources and said the time complexity of KMP algorithm was O(n) [ excluding the space complexity ]

So I will iterate through a list of objects from 1 to N item, searching each item for a pattern match. Once there is a match, I will break out of the loop but that doesn't really affect my evaluation (I think).

So since I iterate all my items, is my Big O notation : O(n^2) since it takes O(n) to find a match and O(n) to iterate through all my items.

Here is my code for some insight:

while(itr.hasNext()){
    //M is the length of our pattern

    i = 0; //index of text to be searched
    j = 0; //index of our pattern

    txt  = itr.next().toString();  //Store the key inside txt string
    N = txt.length(); //length of our text to be search
    
    //Check if the searchText is equal or less than key in the dictionary
    //If our searchText is more than the key length, there is no use of searching
    if(M <= N){
        while (i < N) {
            //Check if the searchText.charAt equals to txt.charAt
            //Increase i,j if matches to compare next character(s)
            if (searchText.charAt(j) == txt.charAt(i)) { 
                j++; 
                i++; 
            }else{ //If the chars at our pattern and text does not match
                if (j != 0) //if it's not the first index of our pattern
                    j--; //reduce one index
                else
                    i++; //otherwise move onto the next index of our text to be searched
            }
            
            //Check whether the length of the searchText equals to the match counter
            //It means that the searchKey exists in our dictionary
            if (j == M) { 
                System.out.println((String.format("%-35s", txt)) + get((K)txt));
                counter++;      //Holds the number of entries found
                j--; 
                break;          //No need to look anymore since there's a match
            }
        }
    }
}

If you have n number of items in your list & on an average each element size is m, then search time complexity would be O(mn). Search time complexity of KMP would be O(m) for each element. You need to multiply it by n.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM