0

I was reading some sorting algorithm here (http://www.sorting-algorithms.com/insertion-sort) and i saw following line

i = 2:n

Can someone explains what does this mean ?

Theoretically I understand that for insertion sort i = size of array. But can someone tell me if i am getting it right ?

2
  • n = a random integer, i = 2:n would mean i is either an integer >= 2, but in this contexts more likely: a range / array from 2 to some higher number n. Commented Sep 23, 2013 at 22:14
  • My best guess would be that it's to denote the range from 2 to n, but I'm not 100% sure. Commented Sep 23, 2013 at 22:14

4 Answers 4

3

This notation is often used to describe ranges of numbers. In your case for i = 2:n can be read as "for every i in numbers 2 to n". If n=4, the loop will run three times with i = 2, i = 3, and i = 4.

Sign up to request clarification or add additional context in comments.

Comments

3

In the pseudocode on the site you linked:

for i = 2:n,
    for (k = i; k > 1 and a[k] < a[k-1]; k--) 
        swap a[k,k-1]

end

The first line means that the second and third lines are repeated n-1 times, and the first time, i = 2, the second time, i = 3, the third time, i = 4, and the last time i = n.

Comments

0

It's basically a loop, similar to

for(int i = 2 ; i <= n ; i++)

Wherea n is defined somewhere above the loop.

Basically: Let i be 2, increment it until it reaches n and use i for each iteration to do some behaviour.

Comments

0

It means iteration with i taking values from 2 to n.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.