Time Complexity for an algorithm

帅比萌擦擦* 提交于 2019-12-31 04:40:09

问题


Am I correct in my explanation when calculating the time complexity of the following algorithm?

  • A HashSet, moduleMarksheetFiles, is being used to add the files that contain the moduleName specified.

    for (File file: marksheetFiles){
         while(csvReader.readRecord()){
             String moduleName = csvReader.get(ModuleName);
    
             if (moduleName.equals(module)){
                   moduleMarksheetFiles.add(file);
             }
         }
     }
    
  • Let m be the number of files

  • Let k be the average number of records per file.
  • As each file is added only once because HashSet does not allow for duplicates. HashSet.add() is O(1) on average and O(n) for worst case.
  • Searching for a record with the specified moduleName involves comparing every record in the file to the moduleName, will take O(n) steps.

Therefore, the average time complexity would be: O((m*k)^2).

Is this correct?

Also, how would you calculate the worst case?

Thanks.

PS. It is not homework, just analysing my system's algorithm to evaluate performance.


回答1:


No, it's not squared, this is O(nk). (Technically, that means it's also O((nk)²), but we don't care.)

Your misconception is that it the worst-case performance of HashSet is what counts here. However, even though a hashtable may have worst-case O(n) insertion time (if it needs to rehash every element), its amortized insertion time is O(1) (assuming your hash function is well behaved; File.GetHashCode presumably is). In other words, if you insert multiple things, so many of them will be O(1) that the occasional O(n) insertion does not matter.

Therefore, we can treat insertions as constant-time operations, so performance is purely dictated by the number of iterations through the inner loop body, which is O(nk).



来源:https://stackoverflow.com/questions/10369061/time-complexity-for-an-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!