I saw this on a book:
BubbleSort( list )
length <-- lenght of list
do {
swapped_pair <-- false
index <-- 1
while index <= length - 1 {
if list[index] > list[index + 1] {
swap( list[index], list[index + 1] )
swapped_pair = true
index <-- index + 1
}
}
} while( swapped = true )
end
In the pseudocode above the index is increased only if list[index] > list[index + 1]
because the index <-- index + 1
is inside the IF-loop.
So if list[index] > list[index + 1]
is not true, then the next lines which are:
swap( list[index], list[index + 1] )
swapped_pair = true
index <-- index + 1
won't be executed. That includes index <-- index + 1
This will cause that if the first two variables are sorted correctly, then the code won't check the next two variables because index won't increase in that case.
And then while index <= length - 1
will always be true because the index is never increased, and maybe the code will be stuck at while index <= length - 1
loop.
Shouldn't the index be placed outside of the IF-loop?
Like this:
BubbleSort( list )
length <-- lenght of list
do {
swapped_pair <-- false
index <-- 1
while index <= length - 1 {
if list[index] > list[index + 1] {
swap( list[index], list[index + 1] )
swapped_pair = true
}
index <-- index + 1
}
} while( swapped = true )
end
So that if list[index] > list[index + 1]
then they are swaped and swapped pair set to true. If if list[index] > list[index + 1]
is not true, the index is increased by 1 by using index <-- index + 1
.
And since while-loop continues because still index <= length - 1
, the process from IF
will repeat again and again until index 0 and 1 to index n-1 and 1.
Is my version of the pseudocode right?
You are correct. The condition in the inner while loop needs to have a way of changing after each iteration.