Counting compares for algorithm analysis -
let's i'm analyzing algorithm , want count compares.
assuming structure this:
if (a == b){   ... } else if (a == c) {   ... } else if (a == d) {   ... } else {   ... }   what's best way count compares?
i'm thinking way go:
int compare = 0  compares++; //will first compare if (a == b){   ... } else if (a == c) {   compares++; //add because got here   ... } else if (a == d) {   compares += 2; //add 2 because of 1 , previous else if   ... } else {   compares += 3; //etc   ... }   is correct?
yes, it's correct, can write more succintly , more robustly (assuming c/c++/js) using comma operator:
if (compares++, == b){   ... } else if (compares++, == c) {   ... } else if (compares++, == d) {   ... } else {   ... }   also, if you're using c++ (or language has operator overloading), can use custom objects , override comparison operator , count there. way have alter type of variables , not rest of code.
Comments
Post a Comment