Sorting Routines

AppleScript routines for sorting a variety of data.

Simple Sort

This sub-routine can be used to sort a list of text strings, or a list of numbers.

set the composer_list to {"Ellington", "Copland", "Bach", "Mozart"}
simple_sort(the composer_list)
--> returns: {"Bach", "Copland", "Ellington", "Mozart"}

set the number_list to {56, 32, -6, 0.01}
simple_sort(the number_list)
--> returns: {"-6", "0.01", "32", "56"}

By default, the sub-routine returns the list in ascending order. If you wish to have the list read in descending order, use the reverse command:

set the composer_list to {"Ellington", "Copland", "Bach", "Mozart"}
get the reverse of simple_sort(the composer_list)
--> returns: {"Mozart", "Ellington", "Copland", "Bach"}

Here's the sub-routine:

Click to open example in the Script Editor applicationA sub-routine to sort a list of text items or a list of numbers:

on simple_sort(my_list)
 set the index_list to {}
 set the sorted_list to {}
 repeat (the number of items in my_list) times
 set the low_item to ""
 repeat with i from 1 to (number of items in my_list)
 if i is not in the index_list then
 set this_item to item i of my_list as text
 if the low_item is "" then
 set the low_item to this_item
 set the low_item_index to i
 else if this_item comes before the low_item then
 set the low_item to this_item
 set the low_item_index to i
 end if
 end if
 end repeat
 set the end of sorted_list to the low_item
 set the end of the index_list to the low_item_index
 end repeat
 return the sorted_list
end simple_sort