First of all, (n-1)!
means (n-1)(n-2)...(2)(1)
. This is clearly not what you want here.
If you count the actual number of iterations it's 0 + 1 + 2 + ... + (n-2) + (n-1)
. Note that there are n
terms in the sum, and that we can pair them off in a way such that the average value of each pair is (n-1)/2
. (Pair the highest and lowest, the second highest and second lowest, etc.) If n
is odd, you'll have one left over that can't be paired, but conveniently its value is also (n-1)/2
. Thus you have n
terms and the average of all terms is (n-1)/2
, so the total sum is n(n-1)/2
.
Now, for big O notation it doesn't matter exactly how many iterations we have -- we just want to know the limit when n
is very large. Note that our number of iterations can be written as (1/2)n^2 - (1/2)n
. For very large n
, the n^2
term is way, way bigger than the n
term, so we drop the n
term. That just leaves us with (1/2)n^2
, but another rule of big O notation is we don't care about the constant factor, so we just write that it's O(n^2).