Sorting algorithms/Insertion sort: Difference between revisions
Content added Content deleted
m (→{{header|AppleScript}}: Tidied.) |
|||
Line 470: | Line 470: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
<lang applescript>-- |
<lang applescript>-- In-place insertion sort |
||
on insertionSort(theList, l, r) |
on insertionSort(theList, l, r) -- Sort items l thru r of 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 |
script o |
||
property lst : theList |
property lst : theList |
||
end script |
end script |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
set currentValue to o's lst's item (l + 1) |
|||
if (highestSoFar > currentValue) then |
|||
set o's lst's item l to currentValue |
|||
else |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
repeat with i from (l + 2) to r |
|||
⚫ | |||
if (highestSoFar > currentValue) then |
if (highestSoFar > currentValue) then |
||
repeat with j from (i - 2) to l by -1 |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
else |
else |
||
⚫ | |||
set highestSoFar to currentValue |
set highestSoFar to currentValue |
||
end if |
end if |
||
⚫ | |||
⚫ | |||
set o's lst's item r to highestSoFar |
|||
repeat with i from (l + 2) to r |
|||
⚫ | |||
if (currentValue < highestSoFar) then |
|||
repeat with j from (i - 2) to l by -1 |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
set item j of o's lst to currentValue |
|||
else |
|||
⚫ | |||
⚫ | |||
end if |
|||
⚫ | |||
-- At the end, ensure that the highest value goes back into the list. |
|||
⚫ | |||
⚫ | |||
return -- nothing |
return -- nothing. |
||
end insertionSort |
end insertionSort |
||
property sort : insertionSort |
property sort : insertionSort |
||
-- |
-- Demo: |
||
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} |
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 |
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. |
||
return aList</lang> |
return aList</lang> |
||