Re: Worst-case Performance of Insertion Sort



InsertionSort( list, N )
list the elements to be put into order
N the number of elements in the list

for i = 2 to N do
newElement = list[ i ]
location = i - 1
while (location >= 1) and (list[ location ] > newElement) do
// move the larger elements out of the way
list[ location + 1 ] = list[ location ]
location = location - 1
end while
list[ location + 1 ] = newElement
end for

In the average case analysis of the algorithm above, would it make
sense to determine the average amount of iterations done by the while
loop?

The while loop will iterate at most i - 1 times so the average amount
of iterations is (0 + 1 + 2 + ... + i - 1) / i = (i - 1) / 2. Since i
varies from 2 to N, the total amount of iterations of the while loop,
on average, is

sum (i = 2 to N) (i - 1) / 2 = sum(i = 1 to N - 1) i / 2 = N(N - 1) /
4 = O(N^2)

which is right. What do you think?




.



Relevant Pages

  • Re: Can this loop be made faster ?
    ... |> Optimisation: maximal 16 iterations for loops which contain one branch, ... |> otherwise the branch-prediction-table will reload (8 clocks penalty ... |> every/after 16 iterations on AMD). ... but if a second Jcc is within the loop then there are more ...
    (alt.lang.asm)
  • Re: Can this loop be made faster ?
    ... increments, of course, the MEMORY at eax ... at least within the loop. ... maximal 16 iterations for loops which contain one branch, ... | routine, and the time is the divided by 100000 after all the calls. ...
    (alt.lang.asm)
  • [Pos] Some quest reward problems identified [Pos]
    ... randart.txt every single time a rand-art is created, ... The tailored reward loop should theoretically trigger a pretty sane ... The number of iterations is fame/5. ... Will look for the rand-art issue later... ...
    (rec.games.roguelike.angband)
  • Re: timeit module: am I missing something obvious?
    ... Why am I passing strings around when functions are ... best of 3 trials: 0.792 usec per loop ... quickly choosing number of iterations. ... - The result from the final pass through the convergence loop ...
    (comp.lang.python)
  • Re: 7.0-CURRENT Hang
    ... The subsequent loop of the following will loop virtually for ever (it t ... doesn't indicate it has the CPUID 0x02 function. ... Do you know what CPUID function 0x00 returns in EAX for your CPU? ... iterations, my guess is that it would take days to loop through this code. ...
    (freebsd-current)