Dry Run an Algorithm
Computer Science and ICT discussion, revision, exam and homework help.
-
Re: Dry Run an Algorithm
take it a piece at a time, and don't get too bogged down in tracing individual steps. Try to get an idea in your head of what each loop is doing first.
ptr <-- ptr + 1
adds one to pointer.
So - basically move up the array from 1 until you find a value less than the value of the variable new.
onto the second loop
values[last+1] <-- values[last]
shifts the value one slot down the array
so - move values[3] into values[4] (last is 3 at the start)
now take one off last, so it's 2
move values[2] into values[3]
keep doing that until last matches ptr
overwrite the value in values[ptr] with the contents of variable new
What it's basically doing is inserting a new value into the array at the correct position. The top loop finds the position, the second loop shuffles stuff down the array to make room for it, the last statement inserts the new value into the gap.
HTH
, sort of :P