i am using this site as a resource
http://www.perlmonks.org/?node_id=573138
I am trying to understand about O notation and it gives two examples of searching two arrays for the same element. First example has O(n^2) as does the second, however the second has an enhancement to it so it runs quicker but still maintains the same O notation, I will paste the code samples below. What I would like to know is how they work, I have limited programming knowledge and am most comfortable in java, i can understand the first I think, just two for loops and check, something like;
for (int i = 0; i < arrarysize ; i++){
for (int j = 0; j < arraysize; j++){
if(getElementFromArray(i).equals(getElementFromArray(j))){
//do something
}
}
}
but how the second works is beyond me, i just don’t get the “enhancement”
for my $i (0 .. $#array) {
for my $j (0 .. $#array) {
next if $j == $i;
# Compare $i, $j
}
}
for my $i (0 .. $#array - 1) {
for my $j ($i + 1 .. $#array) {
# Compare $i, $j
}
}
Think of it in terms of a rectangle of possible
(i, j)values. The first loop compares every pair – so it compares (5, 0) and later compares (0, 5) which will obviously just give the opposite result.The second loop divides that rectangle in half – basically it only checks one “triangle” of it – every value where
j > iso it would check (0, 5) but not (5, 0). This avoids redundancy – but it just means that it’s checkingn*(n-1)/2values instead ofn^2values – it’s stillO(n^2).The second loop in Java would be: