Sorting algorithms/Bubble sort: Difference between revisions

Added AppleScript implementation.
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(Added AppleScript implementation.)
Line 305:
-6 0 2 8 9 9 14 16 23 90
</pre>
 
=={{header|AppleScript}}==
 
In AppleScript, with randomly ordered lists, the time taken to set and check a "has changed" boolean repeatedly over the greater part of the sort generally matches or exceeds any time it may save towards the end. A more effective optimisation, since the greater value in any pair also takes part in the following comparison, is to keep the greater value in a variable and only fetch one value from the list for the next comparison.
 
<lang applescript>-- In-place bubble sort. Sorts the actual list passed.
on bubbleSort(theList, l, r)
script o
property lst : theList
end script
set listLen to (count theList)
if (listLen > 1) then
-- Convert negative and/or transposed range indices.
if (l < 0) then set l to listLen + l + 1
if (r < 0) then set r to listLen + r + 1
if (l > r) then set {l, r} to {r, l}
-- Do the sort.
set lPlus1 to l + 1
repeat with j from r to lPlus1 by -1
set a to item l of o's lst
repeat with i from lPlus1 to j
set b to item i of o's lst
if (a > b) then
set item (i - 1) of o's lst to b
set item i of o's lst to a
else
set a to b
end if
end repeat
end repeat
end if
return -- nothing.
end bubbleSort
 
set aList to {}
repeat with i from 1 to 25
set end of aList to (random number 100)
end repeat
 
-- Sort items 1 thru -1 of a copy.
set sortedCopy to aList's items
bubbleSort(sortedCopy, 1, -1)
 
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set output to "Original: {" & aList & "}
Sorted: {" & sortedCopy & "}"
set AppleScript's text item delimiters to astid
 
return output
</lang>
 
{{output}}
<pre>"Original: {35, 81, 64, 10, 11, 95, 88, 55, 93, 36, 12, 17, 2, 40, 19, 49, 4, 71, 68, 74, 36, 62, 0, 82, 27}
Sorted: {0, 2, 4, 10, 11, 12, 17, 19, 27, 35, 36, 36, 40, 49, 55, 62, 64, 68, 71, 74, 81, 82, 88, 93, 95}"</pre>
 
=={{header|Arendelle}}==
557

edits