I got this pseudocode when studying "Schaum's Outline of Principles of Computer Science" chapter 2:
Insertion_Sort(num_list)
length <-- length of num_list
number_index <-- 2
while{number_index <= length} {
newNum <-- num_list[number_index]
sorted_index <-- number_index - 1
while newNum < num_list[sorted_index] AND sorted_index > 0 {
num_list[sorted_index + 1] <-- num_list[sorted_index]
sorted_index <-- sorted_index - 1
}
num_list[sorted_index + 1] = newNum
}
end
Won't the number_index be stuck at 2?
Shouldn't there be: number_index <-- number_index + 1
after the code num_list[sorted_index + 1] = newNum
?
Is there an error, or it's just I didn't understand the pseudocode?
Can someone explain how this pseudocode works?
Note: I'm not a programmer (very new), I only studied "CODE" by Charles Petzold so far.
You are correct, the pseudo-code is incorrect as it is written because number_index
is never incremented, so the code loops infinitely.
The code is syntactically incorrect in the second to last line with code, using an =
sign to denote assignment instead of the <--
sign that it already established. The names are also not entirely accurate (newNum
isn't actually a new number, just a stored number).
Here is what the code should look like using the given syntax.
Insertion_Sort(num_list)
length <-- length of num_list
number_index <-- 2
while{number_index <= length} {
newNum <-- num_list[number_index]
sorted_index <-- number_index - 1
while newNum < num_list[sorted_index] AND sorted_index + 1 > 0 {
num_list[sorted_index + 1] <-- num_list[sorted_index]
sorted_index <-- sorted_index - 1
}
num_list[sorted_index + 1] <-- newNum
number_index <-- number_index + 1
}
end
Here's an animation showing what the code is supposed to do
And a link to the Wikipedia page on insertion sort (Which has the animation and the correct code).