I need to write an algorithm that checks for uniqueness of a character within a string. I've written the following algorithm:
function unique(s) {
for (var i=0; i<s.length-1; i++) {
for (j=i+1; j<s.length; j++) {
if (s[i] === s[j]) {
return false;
}
}
}
return true;
}
When calculating the number of operations for the worst case scenario, the formula is
n/2x(n-1)=(n^2-n)/2
and the complexity O(n)=n^2
.
Now, I may have written the following algorithm which is not optimized:
function unique(s) {
for (var i=0; i<s.length; i++) {
for (j=0; j<s.length; j++) {
if ((s[i] === s[j]) && (i!==j)) {
return false;
}
}
}
return true;
}
but it gives the same 0(n)=n^2
. So it seems that I can't tell which algorithm is better based on the 0(n)
- is it correct? So why use 0(n)
? And what metric can show that the first algorithm is better than the second one?