Sorting algorithms/Insertion sort: Difference between revisions

Content added Content deleted
m (→‎{{header|AppleScript}}: Minor relabelling.)
Line 487: Line 487:
-- put back into the list until either it's superseded or the end of the sort is reached.
-- put back into the list until either it's superseded or the end of the sort is reached.
set highestSoFar to o's lst's item l
set highestSoFar to o's lst's item l
set currentValue to o's lst's item (l + 1)
set rv to o's lst's item (l + 1)
if (highestSoFar > currentValue) then
if (highestSoFar > rv) then
set o's lst's item l to currentValue
set o's lst's item l to rv
else
else
set highestSoFar to currentValue
set highestSoFar to rv
end if
end if
-- Work through the rest of the range, rotating values back into the sorted group as necessary.
-- Work through the rest of the range, rotating values back into the sorted group as necessary.
repeat with i from (l + 2) to r
repeat with j from (l + 2) to r
set currentValue to o's lst's item i
set rv to o's lst's item j
if (highestSoFar > currentValue) then
if (highestSoFar > rv) then
repeat with j from (i - 2) to l by -1
repeat with i from (j - 2) to l by -1
set thisValue to o's lst's item j
set lv to o's lst's item i
if (thisValue > currentValue) then
if (lv > rv) then
set o's lst's item (j + 1) to thisValue
set o's lst's item (i + 1) to lv
else
else
set j to j + 1
set i to i + 1
exit repeat
exit repeat
end if
end if
end repeat
end repeat
set o's lst's item j to currentValue
set o's lst's item i to rv
else
else
set o's lst's item (i - 1) to highestSoFar
set o's lst's item (j - 1) to highestSoFar
set highestSoFar to currentValue
set highestSoFar to rv
end if
end if
end repeat
end repeat