Sorting algorithms/Insertion sort: Difference between revisions
Content added Content deleted
m (→{{header|AppleScript}}: Tidied.) |
|||
Line 470:
=={{header|AppleScript}}==
<lang applescript>--
on insertionSort(theList, l, r) -- Sort items l thru r of theList.
set listLength to (count theList)▼
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
-- The list as a script property to allow faster references to its items.
script o
property lst : theList
end script
▲ set listLength to (count theList)
▲ if (listLength > 1) then
▲ -- Convert negative and/or transposed range indices.
▲ -- Set up a minor optimisation whereby the latest instance of the highest value so far isn't put back
end if▼
▲ -- into or re-fetched from the list until either it's superseded or the end of the sort is reached.
▲ set highestSoFar to item l of o's lst
repeat with i
if (highestSoFar > currentValue) then
else
set highestSoFar to currentValue
end if
▲ -- Work through the rest of the range, rotating values back into the sorted group as necessary.
set o's lst's item r to highestSoFar
▲ set currentValue to item i of o's lst
▲ set thisValue to item j of o's lst
▲ if (currentValue < thisValue) then
▲ set item (j + 1) of o's lst to thisValue
▲ else
▲ set j to j + 1
▲ exit repeat
▲ end if
▲ end repeat
▲ set item (i - 1) of o's lst to highestSoFar
▲ set highestSoFar to currentValue
▲ end repeat
▲ set o's lst's item r to highestSoFar
▲ end if
return -- nothing
end insertionSort
property sort : insertionSort
--
local aList
set aList to {60, 73, 11, 66, 6, 77, 41, 97, 59, 45, 64, 15, 91, 100, 22, 89, 77, 59, 54, 61}
sort(aList, 1, -1) -- Sort
return aList</lang>
|