-1

This is the pseudocode for insertion sort. According to my teacher the for loop repeats once. Can someone explain why?

for i<-2,n do 
    aux<-v [i] 
    j<-i-1 
    while aux<v [j] AND j>=0 do 
        v[j+1] <-v [j] 
        j<-j-1 
    end while
    v[j+1] <-aux 
end for
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
Mary
  • 11
  • 2
  • 2
    Are you sure that was actually what the teacher said? What exactly would 'repeat once' mean here? – jarmod Apr 26 '23 at 17:01
  • 1
    Well the `for` loop runs from 2 to n. What do you mean by *repeats once*? The for loop only executes once, the loop body hover is executed `n - 2 (+ 1)` times (depending on of n is inclusive or exlusive). – Mushroomator Apr 26 '23 at 17:03
  • when analyzing the complexity of the algorithm , he specified how many times each line repeats . And at the first line he mentioned that the for instruction repeats once. – Mary Apr 26 '23 at 17:08
  • I was thinking he may be refering that the for instruction executes once but iterations in a loop happen n-1 times? not sure though – Mary Apr 26 '23 at 17:15
  • 2
    Have you tried asking the teacher for clarification? This seems like a communication problem, which would more likely be solved by talking with the source than by asking here on stackoverflow. – pjs Apr 26 '23 at 19:07

1 Answers1

0

it does not repeat once , the for loop here has one and only one condition it's n>i (or n>=i not sure xd), and i isn't modified inside the for loop , so each repetition (iteration) is equivalent to 1 , this means the number of digits for i to reach n = the number of iterations so it's (n-i) time

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 28 '23 at 04:54