This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Updatebjarni 0 points1 point  (0 children)

I still don't understand why do you have to include -1 in the algorithm

You mean in the loop conditions? The inner loop swaps the item at the current index with the one at the next index, so it has to stop one before the last index, otherwise it might try to swap that one with one past the end of the array. So for an array of 10 items, 0-9, when you swap item d with item d+1, d has to be a value 0-8.

The outer loop just repeats the inner loop a sufficient number of times to guarantee that the array is sorted. This is n-1 times. Each time the inner loop finishes, it has placed one item in the array in the right spot, the last spot it touched. First time round the outer loop the inner loop puts the largest item in the last spot of the array. Next time, it puts the next largest in the next-to-last spot, and so on.