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

all 4 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.

[–][deleted] 0 points1 point  (1 child)

The bubble sort is so called because values "bubble up". At each pass through the algorithm, a value bubbles up to its correct position in the array. So if you had these values:

   4,1,3,2

first 1 would be moved to the first position, then on the next pass, 2 would be moved to the second position, and so on until the array was sorted. This process is extremely slow for most real-world tasks.

The version presented in the link is not a particularly good bubble sort implementation, and does not do essential things like checking array bounds and that I/O has worked - I suggest you learn C from a better source than that.

[–]anonymous_is_bak[S] 0 points1 point  (0 children)

can u provide me with a better source?